how to convert a string to a Unix timestamp in javascript?

ⅰ亾dé卋堺 提交于 2019-12-17 09:43:59

问题


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.


回答1:


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.

(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(new Date("2013/09/05 15:34:00").getTime()/1000)



回答2:


try

(new Date("2013-09-05 15:34:00")).getTime() / 1000



回答3:


DaMouse404 answer works, but instead of using dashes, you will use slashes:

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.

(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(new Date("2013/09/05 15:34:00").getTime()/1000)



回答4:


For this you should check out the 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();


来源:https://stackoverflow.com/questions/18634087/how-to-convert-a-string-to-a-unix-timestamp-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!