JS: Date Constructor

By Xah Lee. Date: . Last updated: .

Date()

Date()

Return a string that represents the current time when this function is called.

Sample return value: "Tue May 22 2018 18:58:08 GMT-0700 (PDT)"

Arguments to Date() are ignored.

Date() is equivalent to (new Date()).toString().

console.log(
Date()
);
// Tue May 22 2018 18:53:40 GMT-0700 (PDT)
console.log ( Date() === (new Date()).toString() ); // true
// arg to Date() are ignored
console.log( Date(1999) === Date() ); // true

new Date()

new Date() → Return a date object that represents the current datetime when this function is called.

const d = new Date();
console.log ( d.toString ( ) );
// Tue May 22 2018 18:58:08 GMT-0700 (PDT)

new Date(year, month …)

new Date(year, month)

new Date(year, month, day, hours, minutes, seconds, ms)

Return a date object of given (local) datetime.

The year, month are required, other parameters are optional.

The arguments are interpreted as local time. (If you want args to be UTC, use Date.UTC(…). [see JS: Date.UTC] )

Argument format:

  1. year → 4 digits integer.
  2. month → 0 to 11. January is 0.
  3. day → 1 to 31.
  4. hours → 0 to 23.
  5. minutes → 0 to 59.
  6. seconds → 0 to 59.
  7. ms → 0 to 999.
// note: January is 0
console.log(
    (new Date(2016,0,1)).toUTCString()
);
// Fri, 01 Jan 2016 08:00:00 GMT

new Date(milliseconds)

new Date(milliseconds) → Return a date object that represents the datetime of milliseconds since 01 January, 1970 UTC.

This milliseconds is how JavaScript represents datetime internally.

To get milliseconds from date object, use datetime.getTime().

const ms = 1428605303481;

console.log (
 ms === (new Date(ms)). getTime( )
); // true

new Date(date_time_string)

new Date(date_time_string) → Return a date object that represents the datetime in date_time_string.

Note: new Date(date_time_string) is equivalent to new Date( Date.parse ( date_time_string ) )

The Date.parse(date_time_string) return milliseconds, then the new Date(milliseconds) turns that into a date instance.

console.log(
 (new Date("2016-04-08T15:48:22.000Z")) .toString()
 ===
 "Fri Apr 08 2016 08:48:22 GMT-0700 (PDT)"
);

For the format of date_time_string, see JS: Date.parse

Reference

ECMAScript 2015 §Numbers and Dates#sec-date-constructor

Date Topic

  1. JS: Date Tutorial
  2. JS: Date.parse
  3. JS: Compute Date Range
  4. JS: Date Object
  5. JS: Date Constructor
  6. JS: Date.prototype

JS Object Reference

  1. Global
  2. Object
  3. Array
  4. Function
  5. String
  6. RegExp
  7. Date
  8. Set
  9. Map
  10. JSON
  11. Math
  12. Reflect
  13. Number
  14. Boolean
  15. Symbol
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS Basics
  4. JS in Depth
  5. JS Reference
  6. DOM
  7. SVG
  8. JS Misc