根据天数计算年、日期计算

根据具体天数计算共多少年多少月多少天

效果如图:

  
  
  

$(document).ready(function() {
  $("#calculateButton").click(function() {
    var inputDays = parseInt($("#inputDays").val());
    var result = calculateYearsMonthsDays(inputDays);
    $("#result").text("共 " + result.years + " 年 " + result.months + " 个月 " + result.days + " 天");
  });
});

function isLeapYear(year) {
  return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}

function calculateYearsMonthsDays(days) {
  var year = 0;
  var month = 0;
  var day = 0;

  while (days > 0) {
    if (isLeapYear(year) && days >= 366) {
      days -= 366;
      year++;
    } else if (!isLeapYear(year) && days >= 365) {
      days -= 365;
      year++;
    } else {
      var daysInMonth = [31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
      month = 0;
      while (daysInMonth[month] <= days) {
        days -= daysInMonth[month];
        month++;
      }
      day = days;
      break;
    }
  }

  return {
    years: year,
    months: month,
    days: day
  };
}

你可能感兴趣的:(javascript学习笔记,javascript,前端)