MomentJS: How To convert a time in a specific time

2019-08-18 12:00发布

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.

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

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

Tried these methods :

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

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

What I need is 8pm in local time zone.

I also get a warning as below :

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 !

2条回答
2楼-- · 2019-08-18 12:26
  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)

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

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

Putting it all together:

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'

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

查看更多
成全新的幸福
3楼-- · 2019-08-18 12:49

Try this, Hopefully usefull :

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

or else, try on below link: copy below code and paste into javascript area and see the 3rd line of output.

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

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

查看更多
登录 后发表回答