Search code examples
javascriptmomentjsutc

get UTC date using moment in javascript


I am getting a utc date using utcDate = moment.utc(new Date()).format(). But this utcDate is a string, not Date object. By using new Date(utcDate),it is again converting utc date lo my local date. Please help me in getting utc date object. I work in javascript.

utcDate = moment.utc(new Date()).toDate() is converting it to my local date Sun Sep 01 2019 05:30:00 GMT+0530 (India Standard Time)


Solution

  • Using moment.js

    var date = moment();
    console.log(date.format()) // 2019-08-30T11:08:27+05:30
    
    date = moment().utc();
    console.log(date.format()); // 2019-08-30T05:38:27Z
    

    Using Javascript

    var dateObject = new Date();
    dateObject.toLocaleString()
    "8/30/2019, 10:55:19 AM" // My current time
    
    var utcDateObject = new Date( dateObject.getUTCFullYear(), dateObject.getUTCMonth(), dateObject.getUTCDate(), dateObject.getUTCHours(), dateObject.getUTCMinutes(), dateObject.getUTCSeconds() );
    utcDateObject.toLocaleString()
    "8/30/2019, 5:26:04 AM" // UTC time which is 5.5 hours less than my local time