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

Return Date in format ( x years, x months, x days) - JavaScript

本文关键字:JavaScript 格式 日期 返回      更新时间:2023-09-26

如果这个问题已经得到回答,我深表歉意。我到处找,无法完成这项工作。

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

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

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));

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));