如何以年类型获取当前日期

How to get current date in year type

本文关键字:获取 当前日期 类型      更新时间:2023-09-26

我想知道如何获得当前的年,月和日,但在javascript中的年格式

的例子:

当日期为2016/6/15时,格式为2016.5(年中)

function getNumberOfDaysPast(date) {
  var currentMonth = date.getMonth();
  var total = 0;
  for (var i = 0; i < currentMonth; i++) {
    var month = new Date(date.getFullYear(), i, 0);
    total += month.getDate();
  }
  total += date.getDate();
  return total;
}
function dayPercent(date) {
  if (date.getFullYear() % 4 == 0 && date.getFullYear % 100 != 0) {
    return Math.floor((getNumberOfDaysPast(date) / 366) * 100)
  } else {
    return Math.floor((getNumberOfDaysPast(date) / 365) * 100)
  }
}
date = new Date("2016-12-31");
console.log(dayPercent(date))
date = new Date();
console.log(dayPercent(date));
console.log(date.getFullYear() + '.' + dayPercent(date))

更新

考虑到闰年,我们只需要在第4年加一天,而不是第100年

http://www.timeanddate.com/date/leapyear.html

究竟哪一年是闰年?我们几乎每四年在2月29日增加一个闰日。闰日是一个额外的,或闰日,我们把它加到一年中最短的月份,二月。在公历中,确定闰年必须考虑三个标准:一年可以平均除以4;如果一年能被100整除,则不是闰年,除非;年也能被400整除。那就是闰年了。这意味着在公历中,2000年和2400年是闰年,而1800年、1900年、2100年、2200年、2300年和2500年不是闰年。