-3

I want to know how do I can get current year and month and day, but in year format in javascript

example:

when the date is 2016/6/15, the format will be 2016.5 (year's center)

زياد
  • 782
  • 8
  • 12

1 Answers1

2

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

UPDATE

taking leap years into account, we need add a day in only on the 4th year that is not the 100th year

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

Exactly Which Years Are Leap Years? We add a Leap Day on February 29, almost every four years. The leap day is an extra, or intercalary, day and we add it to the shortest month of the year, February. In the Gregorian calendar three criteria must be taken into account to identify leap years: The year can be evenly divided by 4; If the year can be evenly divided by 100, it is NOT a leap year, unless; The year is also evenly divisible by 400. Then it is a leap year. This means that in the Gregorian calendar, the years 2000 and 2400 are leap years, while 1800, 1900, 2100, 2200, 2300 and 2500 are NOT leap years.

WalksAway
  • 2,410
  • 1
  • 15
  • 32