Javascript Date Format








Date Conversion

Date type has three buildin methods to convert date value to string and milliseconds.

  • toLocaleString() returns the date and time in a format appropriate for the locale.
  • toString() returns the date and time with time-zone information.
  • valueOf() returns the milliseconds representation of the date.




Date Conversion Example


var date1 = new Date(2007, 0, 1);          //"January 1, 2007"
var date2 = new Date(2007, 1, 1);          //"February 1, 2007"

console.log(date1.toString());
console.log(date1.toLocaleString());
console.log(date1 < date2);  //true, calling valueOf() from Date
console.log(date1 > date2);  //false, calling valueOf() from Date

The code above generates the following result.

Date-Formatting Methods

There are several Date type methods to format the date as a string.

  • toDateString() - Displays the date's day of the week, month, day of the month, and year in an implementation-specific format.
  • toTimeString() - Displays the date's hours, minutes, seconds, and time zone in an implementation-specific format.
  • toLocaleDateString() - Displays the date's day of the week, month, day of the month, and year in an implementation- and locale-specific format.
  • toLocaleTimeString() - Displays the date's hours, minutes, and seconds in an implementation-specific format.
  • toUTCString() - Displays the complete UTC date in an implementation-specific format.

var date1 = new Date(2007, 0, 1);          //"January 1, 2007"
console.log(date1.toDateString());
console.log(date1.toTimeString());
console.log(date1.toLocaleDateString());
console.log(date1.toLocaleTimeString());
console.log(date1.toUTCString());

The code above generates the following result.