Raghav
Raghav

Reputation: 9630

Convert ISO date string to Date Object without considering timezone

Goal: Convert ISO date string to Date Object without considering timezone

I have a ISO string: 2017-07-23T20:30:00.00Z.

I tried converting that string to Date with the following methods:

new Date('2017-07-23T20:30:00.00Z')

 moment('2017-07-23T20:30:00.00Z').toDate()

 moment.utc('2017-07-23T20:30:00.00Z').toDate()

All are giving the following output: Mon Jul 24 2017 02:00:00 GMT+0530 (India Standard Time)

which is incorrect.

Can you let me know how to get the exact date what was there in string?

Upvotes: 1

Views: 3186

Answers (3)

RobG
RobG

Reputation: 147363

You should always specify the parse format. In this case, just leave off the "Z":

var s = '2017-07-23T20:30:00.00Z';
var m = moment(s, 'YYYY-MM-DDTHH:mm:ss'); // <-- parse format without Z
console.log(m.format())
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

Upvotes: 2

Sotiris Kiritsis
Sotiris Kiritsis

Reputation: 3336

Simply removing the 'Z' character at the end should do the trick for you.

Doing the following will print:

moment('2017-07-23T20:30:00.00').toDate();
// Sun Jul 23 2017 20:30:00 GMT+0300 (GTB Daylight Time)

While this for me prints:

moment('2017-07-23T20:30:00.00Z').toDate();
// Sun Jul 23 2017 23:30:00 GMT+0300 (GTB Daylight Time)

This happens because 'Z' character does not cause the time to be treated as UTC when used in the format. It matches a timezone specifier.

By specifying 'Z' in brackets, you are matching a literal Z, and thus the timezone is left at moment's default, which is the local timezone.

Upvotes: 2

Asik Syed
Asik Syed

Reputation: 1

Try this

var date = new Date('2017-07-23T20:30:00.00Z');
console.log(date.getFullYear()+'/' + (date.getMonth()+1) +
 '/'+date.getDate());

Upvotes: -1

Related Questions