0

Observe the following code and it's output

let str = '2019-06-21';
let dateObj = new Date(str);
console.log(dateObj)

> Thu Jun 20 2019 19:00:00 GMT-0500

The Date object is a day behind than what I specified.

What is a robust way to amend this?

Creating a function to modify the 'DD' portion seems hacky.

I've settled on decrementing the Date object after constructing, but is there a better way?

Why does this behavior happen?

kebab-case
  • 1,732
  • 1
  • 13
  • 24
  • What happens if you change the timezone of either of them ? – Marged Jun 25 '19 at 21:22
  • `dateObj.getUTCDate();` returns `21` though. So it must be timezone. – Subir Kumar Sao Jun 25 '19 at 21:26
  • Look at the time aspect of the date, you also didn't specify it but it is there. So time zone contributes. – Bosco Jun 25 '19 at 21:28
  • If you provide date time with timezone this should be fine. `str = '2019-06-21T00:00:00-05:00'; You can hardcode the non date portion. – Subir Kumar Sao Jun 25 '19 at 21:29
  • Contrary to ISO 8601, the TC39 committee that authors ECMA-262 decided that date-only forms of ISO 8601 timestamps should be interpreted as UTC, not local. – RobG Jun 26 '19 at 01:29

2 Answers2

1

Specify timezone. Currently its defaulting to GMT.

str = '2019-06-21T00:00:00-07:00';
dateObj = new Date(str);
>> Fri Jun 21 2019 00:00:00 GMT-0700 (Pacific Daylight Time)
Subir Kumar Sao
  • 8,171
  • 3
  • 26
  • 47
0

The date object created is in UTC so when you console it you get the day, month and year in your Timezone

let str = '2019-06-21';
let dateObj = new Date(str);

console.log(dateObj.toDateString())
// expected "Thu Jun 20 2019" based on your timezone. 
console.log(dateObj.toUTCString())
// expected "Fri, 21 Jun 2019 00:00:00 GMT"

To create a DateTime based on your timezone, you can either give your timezone or do the following

let d = new Date(Date.now())

d.setDate(21)
d.setHours(0) // if you care to start the day at 00 hrs
d.setMinutes(0)  // if you care to start the day at 00 mins
d.setSeconds(0) // if you care to start the day at 00 seconds

console.log(d.toDateString())
SanthoshN
  • 619
  • 3
  • 15