【问题标题】:MomentJS: How To convert a time in a specific timezone and certain format into millisecondsMomentJS:如何将特定时区和特定格式的时间转换为毫秒
【发布时间】:2023-03-10 02:29:01
【问题描述】:

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

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

这是在 NodeJs 而非浏览器中运行的服务器端。

试过这些方法:

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 和 UTC 晚上 8 点。

我需要的是当地时间晚上 8 点。

我也收到如下警告:

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 

任何正确方向的帮助都会有所帮助。谢谢!

【问题讨论】:

  • 兄弟你试过我的答案了吗?
  • 它应该在 IST 晚上 8 点给出,但是当我在节点服务器中运行时它在 UTC 给出 8 点

标签: javascript node.js momentjs


【解决方案1】:
  1. 要将'2000' 解析为8:00pm,请使用:'HHmm'(如Moment docs on parsing 中所述,解析标记区分大小写。'hh' 用于 12 小时时间格式)

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

这将为您提供“亚洲/加尔各答时区的晚上 8:00”,而不是“UTC 转换到亚洲/加尔各答时区的晚上 8:00”。

把它们放在一起:

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 的格式化功能以您需要的任何格式输出日期/时间 :)

【讨论】:

    【解决方案2】:

    试试这个,希望有用:

    moment('2000','hh:mm').tz('Asia/Kolkata').format('hh:mm');
    

    否则,请尝试以下链接: 复制下面的代码并粘贴到 javascript 区域并查看输出的第 3 行。

    $('#divThai').text(moment('2000','hh:mm').tz('Asia/Kolkata').format('hh:mm'));
    

    http://jsfiddle.net/uq99udc9/4/

    【讨论】:

    • 它工作正常!投赞成票回答并接受这个答案哥们!。
    • 嘿,刚刚试了一下:它没有按预期提供。这是节点服务器,它以 UTC 格式返回相同
    • 兄弟你可以在这里尝试,在 jsfiddle 上然后它工作正常
    猜你喜欢
    • 2018-07-06
    • 1970-01-01
    • 1970-01-01
    • 2021-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-21
    • 2021-08-21
    相关资源
    最近更新 更多