Javascript Date对象返回1969年12月31日

时间:2014-01-20 04:49:38

标签: javascript date d3.js nvd3.js

enter image description here如果您使用毫秒形式的日期,是否需要将其转换为字符串以便Date对象识别它?

"values":[ {x:1390636800000 , y:12} , 
           { x:1390640400000 , y:17} , 
           { x:1390644000000 , y:17}, 
           { x:1390647600000 , y:15}, 
           { x:1390651200000 , y:8} ]

如果是这样,我将如何转换它以便

正确使用它
chart.xAxis
 .axisLabel("Time (s)")
 .tickFormat(function(d){return d3.time.format('%I%p')(new Date(d))});

并没有吐出1969年12月31日的日期?我试图将整个对象字符串化,但这不起作用。有什么建议?感谢您的帮助,对不起,如果这是一个愚蠢的问题

(编辑)这是我正在使用的工作代码,它没有正确显示时间

var chart;

nv.addGraph(function() {
  chart = nv.models.lineChart()
  .options({
   margin: {left: 100, bottom: 100},
   x: function(d,i) { return i},
   showXAxis: true,
   showYAxis: true,
   transitionDuration: 250
 })
 ;

 chart.xAxis
   .axisLabel("Time (s)")
   .tickFormat(function(d){return d3.time.format('%m/%d/%y')(new Date(d))});

 chart.yAxis
   .tickFormat(d3.format('d'))
   ;

 d3.select('#chart1 svg')
   .datum(data1())
   .call(chart);

 nv.utils.windowResize(chart.update);


 chart.dispatch.on('stateChange', function(e) { nv.log('New State:', JSON.stringify(e));    });

 return chart;
});

function data1() {

 return  [
   {
     "values":[ {x:1390636800000 , y:12} , { x:1390640400000 , y:17} , { x:1390644000000 , y:17}, { x:1390647600000 , y:15}, { x:1390651200000 , y:8} ],
  "key": "First Dude "
},
{
  "values": [ { x:1390636800000 , y:16} , { x:1390640400000 , y:16} , { x:1390644000000 , y:16}, { x:1390647600000 , y:12}, { x:1390651200000 , y:5}],
  "key": "Second Dude "
},
{
  "values": [ { x:1390636800000 , y:5} , { x:1390640400000 , y:5} , { x:1390644000000 , y:5}, { x:1390647600000 , y:3}, { x:1390651200000 , y:1}],
  "key": "Third Dude "
}
,
{
  "values": [ { x:1390636800000 , y:8} , { x:1390640400000 , y:18} , { x:1390644000000 , y:18}, { x:1390647600000 , y:9}, { x:1390651200000 , y:7}],
  "key": "Fourth Dude "
}
 ];

}

2 个答案:

答案 0 :(得分:2)

  

如果您使用毫秒形式的日期,是否需要将其转换为字符串以便Date对象识别它?

不,该值必须是数字(例如1390636800000而不是“1390636800000”)。如果提供了字符串,Date将尝试解析它。

如果向Date构造函数提供time value,则假定自1970-01-01T00:00:00Z以来为毫秒。也就是UTC。

因此,如果您所在的时区为UTC -5:00,那么

new Date(0);

将返回一个本地日期和时间为1969-12-31T19:00:00UTC-05:00的对象

答案 1 :(得分:0)

日期不需要以字符串形式转换的毫秒数:

> new Date(1390651200000)
Sat Jan 25 2014 07:00:00 GMT-0500 (EST)

要以您要查找的格式打印时间,您需要更改specifier string

> d3.time.format('%I%p')(new Date(1390640400000))
"04AM"
> d3.time.format('%B/%d/%Y')(new Date(1390640400000))
"January/25/2014"
相关问题