简体   繁体   English

使用date-functions.js库解析为UTC / GMT时间

[英]Parsing into UTC/GMT time with date-functions.js library

Doing this with the date-functions.js library (used eg in datetimepicker jQuery plugin): 使用date-functions.js库执行此操作(例如在datetimepicker jQuery插件中使用):

Date.parseDate('2018-03-10 12:12', 'Y-m-d H:i')

gives: 给出:

Sat Mar 10 2018 12:12:00 GMT+0100 (Paris, Madrid)

How to get the result as Unix timestamp or GMT / UTC time instead? 如何获取结果作为Unix时间戳或GMT / UTC时间呢?

A string like '2018-03-10 12:12' will usually be parsed as local as there is no timezone offset. 像'2018-03-10 12:12'这样的字符串通常会解析为本地字符串,因为没有时区偏移。 It's also not ISO 8601 compliant so using the built-in parser will yield different results in different browsers. 它也不符合ISO 8601,因此使用内置解析器将在不同的浏览器中产生不同的结果。

While you can use a library, to parse it as UTC and get the time value is just 2 lines of code: 虽然可以使用库,但是将其解析为UTC并获取时间值只是两行代码:

 function toUTCTimeValue(s) { var b = s.split(/\\D/); return Date.UTC(b[0],b[1]-1,b[2],b[3],b[4]); } // As time value console.log(toUTCTimeValue('2018-03-10 12:12')); // Convert to Date object and print as timestamp console.log(new Date(toUTCTimeValue('2018-03-10 12:12')).toISOString()); 

Use MomentJS instead. 请改用MomentJS You can specify exactly what format the string you're parsing is in. MomentJS can then provide you with the underlying Date object, unix timestamp as well as convert to UTC. 您可以精确指定要解析的字符串的格式。然后MomentJS可以为您提供基础的Date对象,unix时间戳以及转换为UTC。

 var d = moment('2018-03-10 12:12', 'YYYY-MM-DD HH:mm'); console.log(d.toDate()); console.log(d.unix()); console.log(d.utc().toDate()); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.min.js"></script> 

You could of course also parse the date as UTC too instead of treating it as a local time. 当然,您也可以将日期解析为UTC,而不是将其视为本地时间。

moment.utc('2018-03-10 12:12', 'YYYY-MM-DD HH:mm');

NOTE Bit difficult for me to test UTC as I'm in the UK and GMT and UTC are virtually the same. 注意:由于我在英国,所以我很难测试UTC,GMT和UTC 几乎相同。

 var date = new Date('2018-03-10 12:12'.replace(' ', 'T')); // Unix console.log(Math.floor(date.getTime() / 1000)); // UTC console.log(date.toUTCString()); 

As always, please have a look at the documentation at MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date 与往常一样,请查看MDN上的文档: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

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

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