Home > Software engineering >  String date to format in another type of format JavaScript
String date to format in another type of format JavaScript

Time:12-27

I need a way to parse string date to another format string or date

Tuesday, December 28, 2022   this string date into that format    2022-12-28 

I can make it with hardcoding but I think it is not the best way, any good ideas on how I can format that string?

CodePudding user response:

The way to parse string date to another format string or date like this 2022-12-28 is:

function dateFormat(date) {
    var d = new Date(date),
        month = ''   (d.getMonth()   1),
        day = ''   d.getDate(),
        year = d.getFullYear();

    if (month.length < 2) 
        month = '0'   month;
    if (day.length < 2) 
        day = '0'   day;

    return [year, month, day].join('-');
}
 
console.log(dateFormat('Sun Dec 12,2022'));
  • Related