将毫秒字符串转换为日期对象 Javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5538485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert from string with milliseconds to date object Javascript
提问by deerawan
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. Without milliseconds, I easily convert it with Date.js
为了在 highcharts 中显示它,我必须将它转换为日期或时间对象。没有毫秒,我很容易用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
这个问题有什么解决方案吗?谢谢
回答by Jim Blackler
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.
JS 内置的 Date 类应该能够处理这个,getTime() 可以返回自 1970 年开始(UNIX 时间)以来的毫秒数。不过要注意时区问题;构造函数可能会将日期/时间解释为本地,但自 1970 年以来 getTime() 的毫秒数可能采用 UTC,在难以删除的转换中烘焙。
new Date("2011-04-04 19:27:39.92034").getTime()
1301941659920
回答by KooiInc
Many ways to Rome. The given code will return '(datestr=) 2011-4-4 19:27:39.92'. Is that what you look for?
去罗马的方法很多。给定的代码将返回“(datestr=) 2011-4-4 19:27:39.92”。这就是你要找的吗?
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('');
回答by mariosm
This is simpler and in one line:
这更简单,并且在一行中:
new Date('01/09/2015 06:16:14.123'.split(".")[0])
回答by Thorben
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.
你不能只剪掉那个字符串的最后 6 个字符吗?然后您可以舍入毫秒并最终为您的时间对象添加一秒。