格式的返回日期(x年,x个月,x天) - JavaScript

时间:2016-02-03 23:04:50

标签: javascript date

如果这个问题得到解答,我道歉。我到处寻找,无法做到这一点。

截至目前,我的代码返回了附加示例的天数,但我希望以此格式获得结果 - > 1年,5个月,10天。

有没有更好的方法来获得这个结果?这是我到目前为止的代码,所有的帮助将不胜感激。如果它有帮助,这是bin



function reworkedInBetweenDays(year, month, day){
  
 		var firstDate = new Date();
  		var secondDate =  new Date(year, month-1, day);
 
 		 var diffDays;
 		 var startDate = firstDate.getTime();
 		 var endDate   = secondDate.getTime();
  
 		 diffDays = (startDate - endDate) / 1000 / 86400;
 		 diffDays = Math.round(diffDays - 0.5);

 		 return diffDays;
 	 
	}

	console.log(reworkedInBetweenDays(2014,09,21));




1 个答案:

答案 0 :(得分:1)

function reworkedInBetweenDays(year, month, day) {

   var today = new Date();

   var fromdate = new Date(year, month - 1, day);

   var yearsDiff = today.getFullYear() - fromdate.getFullYear();
   var monthsDiff = today.getMonth() - fromdate.getMonth();
   var daysDiff = today.getDate() - fromdate.getDate();

   if (monthsDiff < 0 || (monthsDiff === 0 && daysDiff < 0))
      yearsDiff--;
   if (monthsDiff < 0)
      monthsDiff += 12;

   if (daysDiff < 0) {
      var fromDateAux = fromdate.getDate();
      fromdate.setMonth(fromdate.getMonth() + 1, 0);
      daysDiff = fromdate.getDate() - fromDateAux + today.getDate();
      monthsDiff--;
   }

   var result = [];

   if (yearsDiff > 0)
      result.push(yearsDiff + (yearsDiff > 1 ? " years" : " year"))
   if (monthsDiff > 0)
      result.push(monthsDiff + (monthsDiff > 1 ? " months" : " month"))
   if (daysDiff > 0)
      result.push(daysDiff + (daysDiff > 1 ? " days" : " day"))

   return result.join(', ');
   
   /* or as an object
   return {
      years: yearsDiff,
      months: monthsDiff,
      days: daysDiff
   }*/
}

console.log(reworkedInBetweenDays(2015, 2, 3));
console.log(reworkedInBetweenDays(2014, 9, 21));
console.log(reworkedInBetweenDays(2016, 1, 31));