Home > Net >  Instruct JavaScript's Date to read a date string dd/mm/yyyy instead of mm/dd/yyyy
Instruct JavaScript's Date to read a date string dd/mm/yyyy instead of mm/dd/yyyy

Time:04-07

I would like to parse the date string 01/04/2022 as April 1st and not like January 4th by JavaScript Date().

Is there any way I can force/instruct javascript's Date() to read a date string as dd/mm/yyyy and not as mm/dd/yyyy?

new Date('01/04/2022') // returns Tue Jan 04 2022 00:00:00 GMT 0100 (Central European Standard Time)

Thanks

CodePudding user response:

It's quite trivial to create a function to do the job

const dmy = s => new Date(...s.split(/\D /).reverse().map((v,i)=> v-(i%2)))
console.log(dmy('01/04/2022').toString())

You could add it to Date ... so you always know where to find it

Date.dmy = s => new Date(...s.split(/\D /).reverse().map((v,i)=> v-(i%2)))
console.log(Date.dmy('01/04/2022').toString())
console.log(Date.dmy('01/13/2022').toString()) // oops, didn't fail

however, the above won't fail on an invalid date

To do so, write it like this

Date.dmy = s => {
    const a = s.split('/');
    return new Date(`${a[1]}/${a[0]}/${a[2]}`);
}
console.log(Date.dmy('01/04/2022').toString())
console.log(Date.dmy('01/13/2022').toString())

CodePudding user response:

You could use the french formating :

const start = Date.now();
const date = new Date(start);
const formatted = date.toLocaleDateString("fr-FR")

CodePudding user response:

The solution may be a string hope the below code helps:

let day = new Date().getDate()
let months = new Date().getMonth();
let year = new Date().getFullYear();

const formatDate = (day, months, year) =>{
    let total = ""
    let error = false
    let errorMessage = ""
    if(day != null && months != null && year != null){
        error = false
        if(months <= 9){
            total = `0${day}/0${months}/${year}`
        }else{
            total = `0${day}/${months}/${year}`;
        }
    }else{
        error = true
        errorMessage = "ERROR, in day, month, or year"
        return errorMessage
    }
    return total
}

// Calling Function
console.log(formatDate(day, months, year))

  • Related