如何将年中的第几天 (0-365) 转换为实际日期并将值设置为 x 轴

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

我有一个文本文件,其中包含一年中的某一天作为一列和一个与之关联的值。

像这样

day value
59   0.2
60   0.6
63  5.07

此处的天列代表一年中的第几天,即 59/365、60/365、63/365。

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

我能够获取此数据并将它们推送为 x 和 y 坐标,并使用 CanvasJS 显示折线图。

但我试图在 x 轴上显示实际日期,以便值对应于特定日期 即,2 月 28 日、3 月 1 日、3 月 6 日。

如何将日期转换为实际日期,然后将其传递到数据点中。

您可以计算毫秒并使用函数 toLocaleString 获取月份和日期。

重要提示: 小心 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))

文档

您可以按以下方式从一年中的某天获取日期:

var dayOfYear = 63;
var initialDate = new Date(2018, 0); // initialized at first day of 2018
var date = new Date(initialDate.setDate(dayOfYear)); // add your dayOfYear