I am working with dates, and when making a date with the new Date() method, I have one day left.
My code:
let prueba = new Date('2018-12-04')
console.log(prueba)
and in the console I have the following date:
Mon Dec 03 2018 21:00:00 GMT-0300 (hora estándar de Argentina)
I mean, I want the date to be December 4th and on console I have one day less.....
Thanks in advance....
When you create a new Date object using that date format ( yyyy-mm-dd ) it takes 00:00:00 as the time and defaults to +0 as the time zone. The date is set as follows: December 4, 2018 at 0:00 in zone +0.
When you print the browser date to the console, it adjusts to the time zone you have set on your computer, in this case GMT-3. When making this adjustment so that you can see the date "translated" to your time zone, these three hours of difference are subtracted and you are left with December 3, 2018 at 9:00 p.m. in zone -3.
The way to make sure that the correct date is left in the Date is to add the time to it as well:
By doing so, the browser assumes that the indicated time is in your time zone and automatically adjusts it to store it correctly.
I recommend this portion of code to compensate for the difference caused by the time zone, which is what is causing that date difference:
You are using the ISO date: "2018-12-04" (The International Standard). Depending on your time zone, it varies between December 03 and December 04. Although in your case it is Argentina, what you should do is add 1 more day to your date so that it shows you the exact date you want. As I reiterate, it is standard Javascript.
Reference: https://www.w3schools.com/js/js_date_formats.asp