简体   繁体   English

Moment JS-将用户提交的日期/时间/时区转换为与时区无关的UTC

[英]Moment JS - convert user-submitted date/time/timezone to timezone-independent UTC

In my Node.js app a user submits a date, time, and timezone (separate form fields). 在我的Node.js应用程序中,用户提交日期,时间和时区(单独的表单字段)。 Using Moment Timezone, I am trying to save the date adjusted for no offset (timezone independent). 使用Moment Timezone,我试图保存调整为无偏移的日期(与时区无关)。

The code below works, but is there a simpler/cleaner way to achieve the same result? 下面的代码有效,但是有没有更简单/更干净的方法来实现相同的结果? Having to multiply the offset by -1 seems hackish: 必须将偏移量乘以-1似乎有点荒谬:

const userDate = new Date(req.body.date + ' ' + req.body.time);
const userTz = req.body.tz;

const offset = moment.tz(userTz).utcOffset();
const utc = moment(userDate).utcOffset(-1*offset).format('YYYY-MM-DD[T]HH:mm:ss');

Example Input: 输入示例:

Date: 09/06/2016 (via Bootstrap date picker)
Time: 07:41:00 (via Bootstrap time picker)
Timezone: America/New_York (UTC/GMT -4 hours)

Returns (correctly): 返回(正确):

2016-09-06T11:41:00Z

Thanks in advance! 提前致谢!

You can use the tz to create a date in user entered timezone, for which there is no direct way in javascript date object. 您可以使用tz在用户输入的时区中创建日期,而在javascript日期对象中没有直接方法。 Once you have the date reconstructed with moment.tz go ahead and convert it to utc , now format it however you want . 一旦使用moment.tz重构了日期,请继续将其转换为utc ,现在可以根据需要对其进行格式化

Also, check your solution( shown in Question ) in a browser running from a different timezone, I am pretty sure that it will give different results. 另外,请不同时区运行的浏览器中检查您的解决方案( 在Question显示 ),我很确定它会给出不同的结果。

 let req = {}; req.body = {date: "09/06/2016", time: "07:41:00", tz: "America/New_York"}; const a = moment .tz(req.body.date+ " " + req.body.time,"MM/DD/YYYY HH:mm:ss" ,req.body.tz) .utc() .format(); console.log(a); 
 <script src="http://momentjs.com/downloads/moment.min.js"></script> <script src="http://momentjs.com/downloads/moment-timezone-with-data-2010-2020.min.js"></script> 

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

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