0

My application receives dates/timestamps in multiple formats and extracts just the date component. If the input date contains the timezone then everything works as expected. If I construct a Date using the constructor with no parameters then it works as expected. The problem is when I construct a date from a string that doesn't have a timezone

e.g. the following works as expected:

import dateFormat from 'dateformat';
const date2 = new Date();
console.log(date2);
console.log(dateFormat(date2, 'isoDate'));

output:

Fri Jun 19 2020 00:23:26 GMT-0700 (Pacific Daylight Time)
2020-06-19

The following does not give me the output I expect

import dateFormat from 'dateformat';
const date = new Date('2010-12-31');
console.log(date);
console.log(dateFormat(date, 'isoDate'));

output:

Dec 30 2010 16:00:00 GMT-0800 (Pacific Standard Time)
2010-12-30

The input to the constructor is the 31st Dec - so I want the output to be 31st Dec.

Thanks in advance

Stuart
  • 143
  • 9
  • 2
    Please consider using a fully fledged library if you're using one for dates anyway. https://date-fns.org/ – N.J.Dawson Jun 19 '20 at 07:50
  • I recommend using moment, here is the link: https://momentjs.com/ – Faizan Shah Jun 19 '20 at 07:52
  • _"It is not recommended to use `Date.parse` as until ES5, parsing of strings was entirely implementation dependent. There are still many differences in how different hosts parse date strings, therefore date strings should be manually parsed (a library can help if many different formats are to be accommodated)."_ (`new Date("...")` implicitly calls `Date.parse()`), [Source](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse) – Andreas Jun 19 '20 at 07:53
  • Thanks @N.J.Dawson - using the date-fns library gave me the correct results – Stuart Jun 19 '20 at 16:14

0 Answers0