0

Why does this give me september 30 rather than oct 1?

var dob = new Date("1999-10-01")
console.log(dob.toString())
  • because you did not specify a timezone. – petey Sep 24 '18 at 15:46
  • It's taking it off your local system time. for me it's BST so shows as GMT+1 – Sean T Sep 24 '18 at 15:46
  • 1
    You're using a non-standard date format, so you're lucky it gives you a date instance at all. It's probably interpreting your date string as a UTC date/time and you're somewhere a few hours behind UTC. – Pointy Sep 24 '18 at 15:46
  • it give me Fri Oct 01 1999 02:00:00 GMT+0200 : maybe it deals with local timezone ? – R. Martin Sep 24 '18 at 15:47
  • It issue of timeZone. It is taking timezone of your local system. Specify a time zone and it will work as expected. – Shubham Gupta Sep 24 '18 at 15:49
  • Thanks for the input guys, I'll look into this – Dominic Lewis Sep 24 '18 at 15:51
  • As @Pointy pointed out the string is indeed parsed as UTC. I assume you want it parsed in your local time? This worked for me `(new Date(1999, 10 - 1, 1)).toString()` or `(new Date("1999-10-01 00:00:00")).toString()` – Roland Starke Sep 24 '18 at 15:52
  • Actually looking again it's *not* non-standard (don't know what I was thinking), it's an ISO date, and if you leave out the time and time zone midnight UTC is assumed. – Pointy Sep 24 '18 at 15:54
  • 1
    @Pointy The format is standard [ISO86001](http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15) – Jonathan Sep 24 '18 at 15:54

2 Answers2

0

You are creating a Date new Date("1999-10-01") and parsing it with the method toString() which is using your local timezone:

var dob = new Date("1999-10-01")

console.log(dob)
console.log(dob.toISOString())

console.log('My local time is different!')
console.log(dob.toLocaleString('es-AR', { timeZone: 'America/Buenos_Aires', timeZoneName: 'long'}))

console.log('Your local time is different?')
console.log(dob.toString())
Aramil Rey
  • 3,387
  • 1
  • 19
  • 30
0

The format you are using is a subset of ISO 8601
When no timezone designator is specified offset Zulu (UTC) is implied in the date constructor.

http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15

All numbers must be base 10. If the MM or DD fields are absent “01” is used as the value. If the HH, mm, or ss fields are absent “00” is used as the value and the value of an absent sss field is “000”. The value of an absent time zone offset is “Z”.

In other words, the format that you are using is valid and it denotes a date-time in UTC. What you are seeing in the console is that time represented in your timezone.

const date = new Date("1999-10-01");

console.log(date.toLocaleDateString('ar-EG'));
console.log(date.toString());
console.log(date.toISOString());
Jonathan
  • 8,771
  • 4
  • 41
  • 78