简体   繁体   中英

Is it possible to convert timestamp to date and time using GMT offset as timezone in moment.js?

I have a couple of GMT time zones like this:

GMT-06:00
GMT-05:00
GMT-04:00

Right now I am using this to convert a time stamp into a date and time like this:

formatted = moment(timestamp).format('YYYY-MM-DD HH:mm:ss z');

Which returns something like 2018-07-02 14:15:03

But the date and time are returned in my local time. I was wondering if moment.js allows me to supply a GMT timezone, and have the date and time be returned in the local time of that specific time zone.

I know that moment.js allows me to do this:

moment(timestamp).tz("Africa/Accra").format('YYYY-MM-DD HH:mm:ss z');

which would return the date and time in that specific "Africa/Accra" time zone, however, I can't use that because I only have GMT time zones right now.

UTC and GMT indicate the same time. Convert the Local time to UTC and then use utcOffset .

 var m = moment(new Date()).utc().utcOffset("-06:00").format("YYYY-MM-DD HH:mm:ss z"); console.log("UTC-06:00 -> " + m); var m = moment(new Date()).utc().utcOffset("-05:00").format("YYYY-MM-DD HH:mm:ss z"); console.log("UTC-05:00 -> " + m); var m = moment(new Date()).utc().utcOffset("-04:00").format("YYYY-MM-DD HH:mm:ss z"); console.log("UTC-04:00 -> " + m);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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