How do I return the correct date string?

58 views Asked by At

When I select a date on my calendar (27 Aug) it returns a 2020-08-26T16:00:00.000Z, how do I return a 2020-08-26 string when I click 26 Aug on my calendar? Currently date.toISOString().slice(0, 10) will return that but only when I click 27 Aug on my calendar

4

There are 4 answers

0
Jason McFarlane On

I would recommend using an external library to help you out. My preference is 'date-fns', its lightweight and has some great documentation.

https://github.com/date-fns/date-fns

You can use the format function to easily give you the value you want

import format from 'date-fns/format'

function dateClicked(date) {
    let formattedString = format(date, 'yyyy-MM-d')

    // Do whatever you need with that string
}
0
Madhan On

import moment from 'moment';

let dateString= moment().format('YYYY-MM-DD');

0
Cornelius On

Thank you for taking the time to answer me guys! But apparently, just a toString() will do and not toISOString()

0
geoffrey.mcgill On

If you are using DateJS, passing a format specifier pattern to toString() will format the date object.

let val = date.toString("yyyy-MM-dd")

console.log(val); // 2020-08-26