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?
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.
To change the default time zone, use moment. tz. setDefault with a valid time zone.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With