使用d3.js将iso格式转换为iso格式的时间戳

时间:2014-05-19 16:13:52

标签: javascript json date unix d3.js

我试图读取包含两列(日期和关闭)的json文件。 Json文件的日期采用unix格式。我尝试将它们转换为iso邮票。这是我的json文件

  [{"date":"\/Date(1397602800000+0100)\/","close":17},
  {"date":"\/Date(1398207600000+0100)\/","close":17},
  {"date":"\/Date(1398639600000+0100)\/","close":1},
  {"date":"\/Date(1398726000000+0100)\/","close":1},
  {"date":"\/Date(1398898800000+0100)\/","close":3},
  {"date":"\/Date(1399071600000+0100)\/","close":12}] 

我的转换代码分为三个步骤 首先在var中接收日期。然后使用"子串"功能只削减要求的日期部分。最后,将其乘以1000以将时间从毫秒转换为秒。 完成后,我将日期解析为d3.time.format.iso.parse格式。 这是我的代码

    d3.json("data.json", function(error, data) {
    data.forEach(function(d) {

 // Convert unix date format to regular format
var dc 
    dc = d.date.substring(6, 24)

    //substring dc Console 
    console.log(dc)

    //convert and multiply it in 1000 to convert the time from milliseconds to seconds
    dc = Date (dc*1000)

    //convert  and seconds dc Console 
    console.log(dc);    

   //parsing the date to iso format  
    dc = parseDate(dc)
    console.log(dc);     
d.close = +d.close;

  });
     // parse format
     ParseDate=d3.time.format.iso.parse

转换部分不起作用。子串dc控制台正常工作。但是,// convert和second dc控制台不能转换unix日期。它打印我的笔记本电脑的日期,它打印当前日期(date.now)......什么错误的人,帮帮我?

1 个答案:

答案 0 :(得分:0)

我认为你的字符串比你需要的字符串长得多,unix时间戳的长度为10,所以不是

dc = d.date.substring(6, 24);

dc = d.date.substring(6, 16)
dc = parseInt( dc) ;// to ensure a correct value

javascript日期对象有一个内置的toISO函数,请尝试:

dc = Date (dc*1000)
console.log( dc.toISOString() );

更新:

var log =  [{"date":"\/Date(1397602800000+0100)\/","close":17},
  {"date":"\/Date(1398207600000+0100)\/","close":17},
  {"date":"\/Date(1398639600000+0100)\/","close":1},
  {"date":"\/Date(1398726000000+0100)\/","close":1},
  {"date":"\/Date(1398898800000+0100)\/","close":3},
  {"date":"\/Date(1399071600000+0100)\/","close":12}] ;


log.forEach(function(d) 
{
    var dc = d.date.substring(6, 16);
    var dc =  parseInt(dc) * 1000;
    var myDate =new Date(dc);
    console.log ( dc );
    console.log( myDate.getTime()); // dc is equal with myDate.getTime() so it's extracted correctly
});