Convert from string with milliseconds to date obje

2019-04-08 17:20发布

I got this problem when dealing with date time conversion. I have timestamp data from postgreSQL database with format like this one

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

In order to display it in highcharts, I have to convert it to date or time object. Without milliseconds, I easily convert it with Date.js

But milliseconds can't be handled with that library. I tried also with Date.parse but always got NaN.

Any solution for this problem? Thank you

4条回答
2楼-- · 2019-04-08 17:33

JS built in Date class should be able to handle this, and getTime() can return milliseconds since start 1970 (UNIX time). 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.

new Date("2011-04-04 19:27:39.92034").getTime()
1301941659920
查看更多
萌系小妹纸
3楼-- · 2019-04-08 17:34

Can't you just cut of the last 6 chars of that string? You might then round the miliseconds and eventually add a second to you time object.

查看更多
Root(大扎)
4楼-- · 2019-04-08 17:40

Many ways to Rome. The given code will return '(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('');
查看更多
做自己的国王
5楼-- · 2019-04-08 17:51

This is simpler and in one line:

new Date('01/09/2015 06:16:14.123'.split(".")[0])
查看更多
登录 后发表回答