Languages
[Edit]
EN

JavaScript - format current date to yyyy-mm-dd (Iso 8601)

5 points
Created by:
Frida-Timms
607

In this article, we would like to show you how to format the current date to yyyy-mm-dd using JavaScript.

Date in yyyy-mm-dd format - JavaScript
Date in yyyy-mm-dd format - JavaScript

Quick solution:

// ONLINE-RUNNER:browser;

// output format: yyyy-mm-dd
function getDateInFormat_yyyy_mm_dd() {
    
    function toString(text, padLength) {
        return text.toString().padStart(padLength, '0');
    }

    let date = new Date();

    let dateTimeNow =
        toString( date.getFullYear(),  4 )
        + '-'  + toString( date.getMonth() + 1, 2 )
        + '-'  + toString( date.getHours(),     2 )
    ;

    return dateTimeNow;
}

console.log(getDateInFormat_yyyy_mm_dd()); // 2021-05-13

Output:

2021-05-13

Next example

// ONLINE-RUNNER:browser;

// output format: yyyy-mm-dd
function getDateInISO_8601() {
    let date = new Date();
    let year = '' + date.getFullYear();
    let month = '' + (date.getMonth() + 1);
    let day = '' + date.getDate();

    if (month.length < 2) {
        month = '0' + month;
    }
    if (day.length < 2) {
        day = '0' + day;
    }
    return year + '-' + month + '-' + day;
}

console.log(getDateInISO_8601()); // 2021-05-13

Output:

2021-05-13

Next example

// ONLINE-RUNNER:browser;

// output format: yyyy-mm-dd
//
function getIso8601Date(date) {
  	if (date == null) {
    	date = new Date();
    }
  
    var year = String(date.getFullYear());
    var month = String(date.getMonth() + 1);
    var day = String(date.getDate());
  
    if (month.length < 2) {
        month = '0' + month;
    }
    if (day.length < 2) {
        day = '0' + day;
    }
  
    return year + '-' + month + '-' + day;
}

// Usage example:

var now = new Date(2021, 05, 13); // 2021-05-13 - e.g. recived from server

console.log(getIso8601Date(now)); // 2021-05-13
console.log(getIso8601Date());    // 2021-05-13

See also

Alternative titles

  1. js - format current date to yyyy-mm-dd
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - Date & Time

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join