Shivprsad Sammbhare
Shivprsad Sammbhare

Reputation: 430

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?

Upvotes: 7

Views: 28288

Answers (5)

Asim
Asim

Reputation: 169

const date = new Date();
console.log(date);
const zone = 'Asia/Karachi';
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>

Upvotes: 0

Amar
Amar

Reputation: 11

function calcTime(city, offset) {

     // create Date object for current location
     var d = new Date();

     // convert to msec
     // add local time zone offset
     // get UTC time in msec
     var utc = d.getTime() + (d.getTimezoneOffset() * 60000);

     // create new Date object for different city
     // using supplied offset
     var nd = new Date(utc + (3600000*offset));

    // return time as a string
    return "The local time in " + city + " is " + nd.toLocaleString();
}

Upvotes: 1

Fraction
Fraction

Reputation: 12954

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>

Upvotes: 13

Zbignev Stankevič
Zbignev Stankevič

Reputation: 42

You could use moment.js documentation:

moment().format('MMMM Do YYYY, h:mm:ss a'); // April 10th 2019, 3:29:36 pm
moment().format('dddd'); // Wednesday
moment().format("MMM Do YY"); // Apr 10th 19
moment().format('YYYY [escaped] YYYY'); // 2019 escaped 2019
moment().format();

Upvotes: -1

naib khan
naib khan

Reputation: 1118

You can do this like the code bellow:

  // your inputs
    var date  = '2019-04-10T20:30:00Z';
    var desiredFormate   = "MM/DD/YYYY h:mm:ss A";  // must match the input
    var zone  = 'Asia/Kuala_Lumpur';

    // construct a moment object
    var m = moment.tz(date , desiredFormate, zone);
    // convert it to utc
    m.utc();

    // format it for output
    var s = m.format(fmt)  // result: 2017-08-31T08:45:00+06:00

Upvotes: -1

Related Questions