Search code examples
javascriptjquerycanvasjs

How to convert day of year (0-365) into actual date and set the values as x axis


I have a text file which contains day of year as a column and a value associated to it.

something like this

day value
59   0.2
60   0.6
63  5.07

Here the day column represents the day in a year i.e, 59/365, 60/365, 63/365.

dataPoints.push({x: parseFloat(x1), y: parseFloat(y1)});// x1 and y1 are variables containing "59" and "0.2" .

I was able to get this data and push them as x and y coordinates and display a line chart using CanvasJS.

But I am trying to display the actual date on the x axis so that the values correspond to a particular date i.e, Feb 28 , March 1 ,March 6.

How can i convert the day into actual date and then pass it into the dataPoints.


Solution

  • You can calculate the milliseconds and use the function toLocaleString to get the month and day.

    Important: Be careful with leap-years.

    var day = 59;
    var date = new Date(day * 24 * 60 * 60 * 1000); // This will place that date in YEAR 1970.
    
    var options = { month: 'short', day: 'numeric' };
    console.log(date.toLocaleString('us', options))

    Docs