Different ways to convert date into a string format

Get support on JavaScript,jQuery, AJAX and other related technology.
Post Reply
admin
Site Admin
Posts: 44

Different ways to convert date into a string format

Post by admin » Sun May 17, 2020 6:47 pm

Convert to String

Code: Select all

var date1 = new Date();
date1.toString();
Returns: "Sun May 17 2020 07:48:48 GMT-0400 (Eastern Daylight Time)"

Convert to Time String

Code: Select all

var date1 = new Date();
date1.toTimeString();
Returns: "07:48:48 GMT-0400 (Eastern Daylight Time)"

Convert to Date String

Code: Select all

var date1 = new Date();
date1.toDateString();
Returns: "Sun May 17 2020"

Convert to UTC String

Code: Select all

var date1 = new Date();
date1.toUTCString();
Returns: "Sun, May 17 2020 11:48:48 GMT"

Convert to ISO String

Code: Select all

var date1 = new Date();
date1.toISOString();
Returns: "2020-05-17T23:49:08.596Z"

Convert to GMT String

Code: Select all

var date1 = new Date();
date1.toGMTString();
Returns: "Sun, 17 May 2020 23:49:08 GMT"

This function has been marked as deprecated so some browsers may not support it in the future. It is suggested to
use toUTCString() instead.

Convert to Locale Date String

Code: Select all

var date1 = new Date();
date1.toLocaleDateString();
Returns: "5/17/2020"

This function returns a locale sensitive date string based upon the user's location by default.

Code: Select all

date1.toLocaleDateString([locales [, options]])
can be used to provide specific locales but is browser implementation specific. For example,

Code: Select all

date1.toLocaleDateString(["zh", "en-US"]);
would attempt to print the string in the Chinese locale using United States English as a fallback. The options parameter can be used to provide specific formatting. For example:

Code: Select all

var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
date1.toLocaleDateString([], options);
would result in
"Thursday, May 17, 2020".

Post Reply