Javascript – Get YYYY-MM-DD string from a Date object

The following piece of code shows you how to get the YYYY-MM-DD formatted string from a Javascript Date Object.

// GET CURRENT DATE
var date = new Date();

// GET YYYY, MM AND DD FROM THE DATE OBJECT
var yyyy = date.getFullYear().toString();
var mm = (date.getMonth()+1).toString();
var dd  = date.getDate().toString();

// CONVERT mm AND dd INTO chars
var mmChars = mm.split('');
var ddChars = dd.split('');

// CONCAT THE STRINGS IN YYYY-MM-DD FORMAT
var datestring = yyyy + '-' + (mmChars[1]?mm:"0"+mmChars[0]) + '-' + (ddChars[1]?dd:"0"+ddChars[0]);

 

Done =)

Reference: StackOverflow – Get String in YYYYMMDD format from JS date object?

Advertisements

9 thoughts on “Javascript – Get YYYY-MM-DD string from a Date object”

  1. The output is of string type.Is there any way to convert string to date object with the dd/MM/yyyy format and output after format change is of date type and not of string,

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s