简体   繁体   English

从具有毫秒的字符串转换为日期对象Javascript

[英]Convert from string with milliseconds to date object Javascript

I got this problem when dealing with date time conversion. 处理日期时间转换时遇到了这个问题。 I have timestamp data from postgreSQL database with format like this one 我有来自postgreSQL数据库的时间戳数据,格式就像这样

"2011-04-04 19:27:39.92034" “2011-04-04 19:27:39.92034”

In order to display it in highcharts, I have to convert it to date or time object. 为了在highcharts中显示它,我必须将它转换为日期或时间对象。 Without milliseconds, I easily convert it with Date.js 没有毫秒,我可以使用Date.js轻松转换它

But milliseconds can't be handled with that library. 但是该库无法处理毫秒。 I tried also with Date.parse but always got NaN. 我也试过Date.parse但总是得到NaN。

Any solution for this problem? 解决这个问题的任何方法? Thank you 谢谢

JS built in Date class should be able to handle this, and getTime() can return milliseconds since start 1970 (UNIX time). 在Date类中构建的JS应该能够处理这个,并且getTime()可以从1970年开始(UNIX时间)返回毫秒。 Watch out for time zone issues though; 注意时区问题; the constructor may interpret the date/time as being local, but getTime()'s milliseconds since 1970 may be in UTC, baking in a conversion that is difficult to remove. 构造函数可能会将日期/时间解释为本地,但自1970年以来getTime()的毫秒数可能是UTC,烘焙的转换难以删除。

new Date("2011-04-04 19:27:39.92034").getTime()
1301941659920

Many ways to Rome. 罗马的方式很多。 The given code will return '(datestr=) 2011-4-4 19:27:39.92'. 给定的代码将返回'(datestr =)2011-4-4 19:27:39.92'。 Is that what you look for? 这就是你要找的?

var darr = '2011-04-04 19:27:39.92034'.split('.')
  , dat=new Date(darr[0])
  , datestr = '';
dat.setMilliseconds(Math.round(darr[1]/1000));
datestr = [ [dat.getFullYear(),dat.getMonth()+1,dat.getDate()].join('-')
            ,' ', 
            [dat.getHours(),dat.getMinutes(),dat.getSeconds()].join(':')
            ,'.',
            dat.getMilliseconds()
          ].join('');

这更简单,并且在一行中:

new Date('01/09/2015 06:16:14.123'.split(".")[0])

Can't you just cut of the last 6 chars of that string? 难道你不能只切断那个字符串的最后6个字符吗? You might then round the miliseconds and eventually add a second to you time object. 然后你可能会在几毫秒内完成并最终为你的时间对象增加一秒。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM