How to Make Format date in JavaScript

BOOKC, this time share about How to Make Format date in JavaScript

This time I will share a little calm how to make a date format in javascript like "yyyy-mm-dd" or for example 2014-01-11.

Problem : I have a date formatted Sun 11 May 2014. How can I convert it to 2014-05-11 using JavaScript?

The solution you can use the code below:

function formatDate(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(formatDate('Sun May 11,2014'));

Usage example:

console.log(formatDate('Sun May 11,2014'));

Output:

2014-05-11

Hopefully this article about creating or customizing a date format in javascript is useful. And don't forget to share it.

Bookc
Admin

Hopefully the information we provide can be useful.

Press ESC to close