0

I need to get the yyyy-mm-dd of today on const today2. I'm trying this:

const today = new Date();
console.log('today', today)
// today Wed Mar 11 2020 23:13:35 GMT-0300 (hora de verano de Chile)
const today2 = new Date().toISOString().slice(0,10);
console.log('today2', today2)
// today2 2020-03-12

I need to get 2020-03-11 but I'm getting 2020-03-12 why? I don't want to use moment

pmiranda
  • 7,602
  • 14
  • 72
  • 155
  • 2
    Seems like a timezone issue - by removing the GMT-0300 what you are doing is getting the date of now +3hours - which is giving the next date since the time is 11pm. - or in effect you are getting Wed Mar 12 2020 02:13:35 – gavgrif Mar 12 '20 at 02:21
  • `23:13:35 GMT-0300` is `02:13:35` on the next day - you're using ISO string, therefore GMT, therefore the value is correct – Jaromanda X Mar 12 '20 at 02:22
  • Check Local TimeZone in your computer. – superup Mar 12 '20 at 02:46

3 Answers3

2

Try this:

const today = new Date();
const today2 = new Date(today.getTime()  - (today.getTimezoneOffset() * 60000)).toISOString().slice(0,10);

Using toISOString() converts the timezone to UTC(standard time)

Markipe
  • 616
  • 6
  • 16
1

Try this function..

    export const getTodayDate = () => {
            var today = new Date();
            var dd = (today.getDate()).toString();
            var mm = (today.getMonth() + 1).toString(); 
            var yyyy = (today.getFullYear()).toString();

            if (parseInt(dd) < 10) {
                dd = '0' + dd;
            } 

            if (parseInt(mm) < 10) {
                mm = '0' + mm;
            } 

            return yyyy + '-' + mm + '-' + dd;
     }

const today2 = getTodayDate();
console.log(today2);
Zar Ni Ko Ko
  • 352
  • 2
  • 7
0

I got it from: https://stackoverflow.com/a/50130338/3541320

const today = new Date();
const todayYYYMMDD = new Date(today.getTime() - (today.getTimezoneOffset() * 60000 ))
  .toISOString()
  .split("T")[0];
pmiranda
  • 7,602
  • 14
  • 72
  • 155