0

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?

Raghav
  • 8,772
  • 6
  • 82
  • 106
  • Possible duplicate of [Convert ISO Date to Date Format yyyy-mm-dd format in javascript](https://stackoverflow.com/questions/25159330/convert-iso-date-to-date-format-yyyy-mm-dd-format-in-javascript) – Hassan Imam Jul 18 '17 at 06:13
  • `'2017-07-23T20:30:00.00Z.'.substring(0,10);` to get the date. – Hassan Imam Jul 18 '17 at 06:14
  • @HassanImam—not a duplicate. The OP wants the date to be treated as local, the UTC date will be different to the local date for the period of the local timezone offset every day. In timezone +0530, it will be "tomorrow" in UTC terms until 5:30 am local time or from 6:30 pm UTC time. – RobG Jul 18 '17 at 09:56
  • @RobG Isn't OP want to extract out the date from his original ISO date string? Even his example is pointing out the same. – Hassan Imam Jul 18 '17 at 17:10
  • @HassanImam—In regard to your first comment, the suggested duplicate uses the timezone. For your second, the OP wants to convert the string to a Date object, your suggestion of using just the date part fails as `new Date('2017-07-23')` will (in most browsers) treat the string as UTC (so back to the original issue where UTC date doesn't match the local date). – RobG Jul 18 '17 at 23:03

3 Answers3

2

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.

Sotiris Kiritsis
  • 3,178
  • 3
  • 23
  • 31
1

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>
RobG
  • 142,382
  • 31
  • 172
  • 209
-1

Try this

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