简体   繁体   中英

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

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.

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)

尝试

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

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)

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();

I would go with date parse myself since it is the native solution. MDN documentation.

const datetimeString = '04 Dec 1995 00:12:00 GMT';
const unixTimestamp = Date.parse(datetimeString);
// unixTimestamp = 818035920000

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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