简体   繁体   English

如何在javascript中将字符串转换为Unix时间戳?

[英]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.我想在javascript "2013-09-05 15:34:00"字符串"2013-09-05 15:34:00"转换为Unix时间戳。 Can any one tell how to do that?任何人都可以告诉如何做到这一点? thanks.谢谢。

You can initialise a Date object and call getTime() to get it in unix form.您可以初始化一个 Date 对象并调用 getTime() 来以 unix 形式获取它。 It comes out in milliseconds so you'll need to divide by 1000 to get it in seconds.它以毫秒为单位出现,因此您需要除以 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)

尝试

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

DaMouse404 answer works, 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.您可以初始化一个 Date 对象并调用 getTime() 来以 unix 形式获取它。 It comes out in milliseconds so you'll need to divide by 1000 to get it in seconds.它以毫秒为单位出现,因此您需要除以 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)

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

I would go with date parse myself since it is the native solution.我会自己使用日期解析,因为它是本机解决方案。 MDN documentation. MDN 文档。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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