Search code examples
javascriptdatetimemomentjsdate-conversionlocaltime

How to convert "2017-07-27T08:02:17+0200" to local date-time and zone using moment.js


How to convert "2017-07-27T08:02:17+0200" to local date-time and zone using moment.js?

Here 08:02:17 is hour:minute:second and +0200 is time-zone. My local time-zone is GMT+6. I want to convert that date as my local date-time and zone. I've tried this so far:

moment.utc('2017-07-27T08:02:17+0200','YYYY-MM-DDThh:mm:ssZZ').local()

But it is returning Invalid Date by moment.js


Solution

  • As stated here

    By default, moment parses and displays in local time.

    Your input string includes UTC offset, so you can simply use moment(String, String).

    Note that as stated here:

    Moment's string parsing functions like moment(string) and moment.utc(string) accept offset information if provided, but convert the resulting Moment object to local or UTC time.

    so there is no need to use local().

    var m = moment('2017-07-27T08:02:17+0200', 'YYYY-MM-DDTHH:mm:ssZZ')
    console.log(m.format());
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>