Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a decimal year value into a Date in Javascript?

OK, this is basically a Javascript version of How can I convert a decimal year value into a Date in Ruby? and not exactly a duplicate of Javascript function to convert decimal years value into years, months and days

Input:

2015.0596924

Desired output:

January 22, 2015

I have solved it (see below), but I expect (just like the Ruby version of this question) that there is a better way.

like image 563
Alien Life Form Avatar asked Sep 08 '25 14:09

Alien Life Form


2 Answers

The other solution would be:

  1. Create date for given year (integer part)
  2. Calculate days from reminder (decimal part) and convert to milliseconds
  3. Add milliseconds to (1)

In script:

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

function convertDecimalDate(decimalDate) {
    var year = parseInt(decimalDate);
    var reminder = decimalDate - year;
    var daysPerYear = leapYear(year) ? 366 : 365;
    var miliseconds = reminder * daysPerYear * 24 * 60 * 60 * 1000;
    var yearDate = new Date(year, 0, 1);
    return new Date(yearDate.getTime() + miliseconds);
}

var date = convertDecimalDate(2015.0596924);
console.log(date);

You can play with it on this Fiddle.

like image 102
skobaljic Avatar answered Sep 10 '25 04:09

skobaljic


JavaScript will resolve the dates for you if you add too much time. See demonstration below. The solution below doesn't calculate the leap year based on the algorithm, but takes next year's date and subtracts it from this year. This assumes that the JavaScript specification properly calculates leap years.

See Mozilla Docs for more info.

function decimalDateToJsDate(time) {
  var year = Math.floor(time);
  var thisYear = new Date(year, 0, 1);
  var nextYear = new Date(year + 1, 0, 1);
  var millisecondsInYear = nextYear.getTime() - thisYear.getTime();
  var deltaTime = Math.ceil((time - year) * millisecondsInYear);
  thisYear.setMilliseconds(deltaTime);
  return thisYear;
}

document.getElementById("output").innerHTML = decimalDateToJsDate(2015.0596924);
<pre id="output"></pre>
like image 26
Pete Avatar answered Sep 10 '25 02:09

Pete