Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Momentjs: How to convert date/time of one timezone to UTC date/time

I have a date/time with a timezone and want to convert it into UTC

const date = '2019-04-10T20:30:00Z';
const zone = 'Asia/Kuala_Lumpur';
const utcDate = moment(date).tz(zone).utc().format();
console.log('UTC Date : ', utcDate);

is my date variable is in standard formate for UTC? How to cast this time zone to another time zone?

like image 570
Shivprsad Sammbhare Avatar asked Apr 10 '19 12:04

Shivprsad Sammbhare


People also ask

How do you convert date to UTC format?

The ToUniversalTime method converts a DateTime value from local time to UTC. To convert the time in a non-local time zone to UTC, use the TimeZoneInfo. ConvertTimeToUtc(DateTime, TimeZoneInfo) method. To convert a time whose offset from UTC is known, use the ToUniversalTime method.

How do I change timezone in MomentJS?

To change the default time zone, use moment. tz. setDefault with a valid time zone.

How do you convert UTC to specific time zones?

The best way to do this is simply to use TimeZoneInfo. ConvertTimeFromUtc . // you said you had these already DateTime utc = new DateTime(2014, 6, 4, 12, 34, 0); TimeZoneInfo tzi = TimeZoneInfo. FindSystemTimeZoneById("Pacific Standard Time"); // it's a simple one-liner DateTime pacific = TimeZoneInfo.


1 Answers

The UTC timezone is denoted by the suffix "Z" so you need to remove "Z" and use moment.tz(..., String) instead of moment().tz(String) because the first create a moment with a time zone and the second is used to change the time zone on an existing moment:

const date = '2019-04-10T20:30:00';
const zone = 'Asia/Kuala_Lumpur';
const utcDate = moment.tz(date, zone).utc().format();
console.log('UTC Date : ', utcDate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.min.js"></script>
like image 172
Fraction Avatar answered Sep 30 '22 06:09

Fraction