Search code examples
javascriptdatetimemomentjsutcdate-conversion

Moment js utc conversions not working as expected, behind date object value


I am trying to convert a particular date to utc(save it in db) and after fetching it show it as local time. When I use moment there is always a half an hour delay as compared to js Date object,any idea why?

Date is 8th May 2016, browser timezone is India

Convert Date to Utc: Moment:

moment('2016-05-08', 'YYYY-MM-DD').utc().format('YYYY-MM-DD HH:MM:SS Z')
Result: "2016-05-07 18:05:00 +00:00"

Date:

new Date('2016/05/08').toUTCString()
Result: "Sat, 07 May 2016 18:30:00 GMT"

I believe 18:30 is the right answer and not 18:05

From Utc to date: Moment:

moment('2016-05-07 18:05:00 +00:00', 'YYYY-MM-DD HH:MM:SS Z').format('YYYY-MM-DDTHH:MM:SS')
Result: "2016-05-07T23:05:00" //This should be 8th May since I had started with 8th May

Date:

new Date("Sat, 07 May 2016 18:30:00 GMT").toString()
Result: "Sun May 08 2016 00:00:00 GMT+0530 (India Standard Time)" //this is the correct answer since I had initially started with 8Th May.

Any reason why moment has this lag?


Solution

  • You are using capital M instead of mm for minutes, and it's giving you months. Switch to little m and everything is fine.

    moment('2016-05-08', 'YYYY-MM-DD').utc().format('YYYY-MM-DD HH:mm:ss Z')
    "2016-05-07 18:30:00 +00:00"