string 如何在javascript中将字符串转换为Unix时间戳?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18634087/
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
how to convert a string to a Unix timestamp in javascript?
提问by Newbie
I want to convert a string "2013-09-05 15:34:00"
into a Unix timestamp in javascript. Can any one tell how to do that? thanks.
我想"2013-09-05 15:34:00"
在 javascript 中将字符串转换为 Unix 时间戳。任何人都可以告诉如何做到这一点?谢谢。
回答by Mousius
You can initialise a Date object and call getTime() to get it in unix form. It comes out in milliseconds so you'll need to divide by 1000 to get it in seconds.
您可以初始化一个 Date 对象并调用 getTime() 来以 unix 形式获取它。它以毫秒为单位出现,因此您需要除以 1000 才能在几秒钟内得到它。
(new Date("2013/09/05 15:34:00").getTime()/1000)
It may have decimal bits so wrapping it in Math.round would clean that.
它可能有十进制位,所以将它包装在 Math.round 中可以清除它。
Math.round(new Date("2013/09/05 15:34:00").getTime()/1000)
回答by Mohsen
try
尝试
(new Date("2013-09-05 15:34:00")).getTime() / 1000
回答by cumanacr
DaMouse404answerworks, but instead of using dashes, you will use slashes:
DaMouse404答案有效,但不是使用破折号,而是使用斜线:
You can initialise a Date object and call getTime() to get it in unix form. It comes out in milliseconds so you'll need to divide by 1000 to get it in seconds.
您可以初始化一个 Date 对象并调用 getTime() 来以 unix 形式获取它。它以毫秒为单位出现,因此您需要除以 1000 才能在几秒钟内得到它。
(new Date("2013/09/05 15:34:00").getTime()/1000)
It may have decimal bits so wrapping it in Math.round would clean that.
它可能有十进制位,所以将它包装在 Math.round 中可以清除它。
Math.round(new Date("2013/09/05 15:34:00").getTime()/1000)
回答by Mahus
For this you should check out the moment.s-library
为此,您应该查看 moment.s-library
Using that you could write something like:
使用它,您可以编写如下内容:
newUnixTimeStamp = moment('2013-09-05 15:34:00', 'YYYY-MM-DD HH:mm:ss').unix();