MomentJS:如何将特定时区和某种格式的时间转换为毫秒 [英] MomentJS: How To convert a time in a specific timezone and certain format into milliseconds

查看:2029
本文介绍了MomentJS:如何将特定时区和某种格式的时间转换为毫秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某个时区,我有一个格式为"hhmm"的时间"2000",例如亚洲/加尔各答". 尝试了其他答案中提到的几种方法,但没有一个给出正确的答案.

I have a time "2000" in format "hhmm" for certain timezone say 'Asia/Kolkata'. Tried a couple of approaches mentioned in other answers but none are giving the right answers.

预期 :当地时区的确切时间(亚洲/加尔各答(当地)晚上8点)

Expected : Exact time in local timezone (8pm in Asia/Kolkata)

这是在NodeJ而不是浏览器中在服务器端运行的.

This is being run server side in NodeJs not a browser .

尝试了以下方法:

let localTime1 = moment('2000').tz('Asia/Kolkata');
let localTime2 = moment('2000','hhmm').tz('Asia/Kolkata');
let localTime3 = moment('2000', 'hhmm', 'Asia/Kolkata');

两者的值都为1556827200000,在当地时区为1:30 pm,在UTC为8 pm.

Both give a value 1556827200000 which is 1:30 pm in local timezone and 8 pm in UTC .

我需要的是当地时区的晚上8点.

What I need is 8pm in local time zone.

我还会收到如下警告:

Deprecation warning: value provided is not in a recognized RFC2822 or ISO 
format. moment construction falls back to js Date(), which is not reliable             
across all browsers and versions. Non RFC2822/ISO date formats are 
discouraged and will be removed in an upcoming major release. Please refer to 
http://momentjs.com/guides/#/warnings/js-date/ for more info.
Arguments: 
[0] _isAMomentObject: true, _isUTC: false, _useUTC: false, _l: undefined, _i: 
2000, _f: undefined, _strict: undefined, _locale: [object Object]
Error
at Function.createFromInputFallback (/user_code/node_modules/moment-timezone/node_modules/moment/moment.js:320:98)
at configFromString (/user_code/node_modules/moment-timezone/node_modules/moment/moment.js:2385:15)
at configFromInput (/user_code/node_modules/moment-timezone/node_modules/moment/moment.js:2611:13)
at prepareConfig 

任何在正确方向上的帮助都会有所帮助.谢谢!

Any help in the right direction would be helpful. Thanks !

推荐答案

  1. 要将'2000'解析为8:00pm,请使用:'HHmm'(如在解析过程中的文档,解析令牌区分大小写.'hh'适用于12小时时间格式)

  1. To parse '2000' as 8:00pm use: 'HHmm' (As noted in the Moment docs on parsing, the parsing tokens are case-sensitive. 'hh' is for 12 hour time formats)

要将日期/时间解析为特定时区,请使用 moment.tz(..., String);函数.

To parse a date/time into a particular timezone use the moment.tz(..., String); function.

这将为您提供亚洲/加尔各答时区的8:00 pm",而不是"UTC 已转换为亚洲/加尔各答时区的8:00 pm".

This will give you "8:00pm in the Asia/Kolkata timezone", rather than "8:00pm UTC converted to Asia/Kolkata timezone".

将它们放在一起:

const moment = require('moment-timezone');

let localTime1 = moment.tz('2000', 'HHmm', 'Asia/Kolkata')

console.log(localTime1.toString());
// 'Thu May 02 2019 20:00:00 GMT+0530'

当然,您可以使用Moment的格式化功能以所需的任何格式输出日期/时间:)

Of course you can use Moment's formatting functions out output the date/time in whatever format you need :)

这篇关于MomentJS:如何将特定时区和某种格式的时间转换为毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆