Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 1062490 of Date

  • Revision slug: Web/JavaScript/Reference/Global_Objects/Date
  • Revision title: Date
  • Revision id: 1062490
  • Created:
  • Creator: xerotalent
  • Is current revision? No
  • Comment Fix broken link to two digit years example
Tags: 

Revision Content

{{JSRef}}

Creates a JavaScript Date instance that represents a single moment in time. Date objects are based on a time value that is the number of milliseconds since 1 January, 1970 UTC.

Syntax

new Date();
new Date(value);
new Date(dateString);
new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);

Note: JavaScript Date objects can only be instantiated by calling JavaScript Date as a constructor: calling it as a regular function (i.e. without the {{jsxref("Operators/new", "new")}} operator) will return a string rather than a Date object; unlike other JavaScript object types, JavaScript Date objects have no literal syntax.

Parameters

Note: Where Date is called as a constructor with more than one argument, if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013, 13, 1) is equivalent to new Date(2014, 1, 1), both create a date for 2014-02-01 (note that the month is 0-based). Similarly for other values: new Date(2013, 2, 1, 0, 70) is equivalent to new Date(2013, 2, 1, 1, 10) which both create a date for 2013-03-01T01:10:00.

Note: Where Date is called as a constructor with more than one argument, the specifed arguments represent local time. If UTC is desired, use new Date({{jsxref("Date.UTC()", "Date.UTC(...)")}}) with the same arguments.

value
Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC (Unix Epoch; but consider that most Unix time stamp functions count in seconds).
dateString
String value representing a date. The string should be in a format recognized by the {{jsxref("Date.parse()")}} method (IETF-compliant RFC 2822 timestamps and also a version of ISO8601).

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.

year
Integer value representing the year. Values from 0 to 99 map to the years 1900 to 1999. See the {{anch("Two_digit_years_map_to_1900_-_1999", "example below")}}.
month
Integer value representing the month, beginning with 0 for January to 11 for December.
day
Optional. Integer value representing the day of the month.
hour
Optional. Integer value representing the hour of the day.
minute
Optional. Integer value representing the minute segment of a time.
second
Optional. Integer value representing the second segment of a time.
millisecond
Optional. Integer value representing the millisecond segment of a time.

Description

  • If no arguments are provided, the constructor creates a JavaScript Date object for the current date and time according to system settings.
  • If at least two arguments are supplied, missing arguments are either set to 1 (if day is missing) or 0 for all others.
  • The JavaScript date is based on a time value that is milliseconds since midnight 01 January, 1970 UTC. A day holds 86,400,000 milliseconds. The JavaScript Date object range is -100,000,000 days to 100,000,000 days relative to 01 January, 1970 UTC.
  • The JavaScript Date object provides uniform behavior across platforms. The time value can be passed between systems to represent the same moment in time and if used to create a local date object, will reflect the local equivalent of the time.
  • The JavaScript Date object supports a number of UTC (universal) methods, as well as local time methods. UTC, also known as Greenwich Mean Time (GMT), refers to the time as set by the World Time Standard. The local time is the time known to the computer where JavaScript is executed.
  • Invoking JavaScript Date as a function (i.e., without the {{jsxref("Operators/new", "new")}} operator) will return a string representing the current date and time.

Properties

{{jsxref("Date.prototype")}}
Allows the addition of properties to a JavaScript Date object.
Date.length
The value of Date.length is 7. This is the number of arguments handled by the constructor.

Methods

{{jsxref("Date.now()")}}
Returns the numeric value corresponding to the current time - the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.
{{jsxref("Date.parse()")}}
Parses a string representation of a date and returns the number of milliseconds since 1 January, 1970, 00:00:00, UTC.

Note: Parsing of strings with Date.parse is strongly discouraged due to browser differences and inconsistencies.

{{jsxref("Date.UTC()")}}
Accepts the same parameters as the longest form of the constructor (i.e. 2 to 7) and returns the number of milliseconds since 1 January, 1970, 00:00:00 UTC.

JavaScript Date instances

All Date instances inherit from {{jsxref("Date.prototype")}}. The prototype object of the Date constructor can be modified to affect all Date instances.

Date.prototype Methods

{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/prototype', 'Methods')}}

Examples

Several ways to create a Date object

The following examples show several ways to create JavaScript dates:

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.

var today = new Date();
var birthday = new Date('December 17, 1995 03:24:00');
var birthday = new Date('1995-12-17T03:24:00');
var birthday = new Date(1995, 11, 17);
var birthday = new Date(1995, 11, 17, 3, 24, 0);

Two digit years map to 1900 - 1999

In order to create and get dates between the years 0 and 99 the {{jsxref("Date.prototype.setFullYear()")}} and {{jsxref("Date.prototype.getFullYear()")}} methods should be used.

var date = new Date(98, 1); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)

// Deprecated method, 98 maps to 1998 here as well
date.setYear(98);           // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)

date.setFullYear(98);       // Sat Feb 01 0098 00:00:00 GMT+0000 (BST)

Calculating elapsed time

The following examples show how to determine the elapsed time between two JavaScript dates in millisconds.

Due to the differing lengths of days (due to daylight saving changeover), months and years, expressing elapsed time in units greater than hours, minutes and seconds requires addressing a number of issues and should be thoroughly researched before being attempted.

// using Date objects
var start = Date.now();

// the event to time goes here:
doSomethingForALongTime();
var end = Date.now();
var elapsed = end - start; // elapsed time in milliseconds
// using built-in methods
var start = new Date();

// the event to time goes here:
doSomethingForALongTime();
var end = new Date();
var elapsed = end.getTime() - start.getTime(); // elapsed time in milliseconds
// to test a function and get back its return
function printElapsedTime(fTest) {
  var nStartTime = Date.now(),
      vReturn = fTest(),
      nEndTime = Date.now();

  console.log('Elapsed time: ' + String(nEndTime - nStartTime) + ' milliseconds');
  return vReturn;
}

yourFunctionReturn = printElapsedTime(yourFunction);

Note: In browsers that support the {{domxref("window.performance", "Web Performance API", "", 1)}}'s high-resolution time feature, {{domxref("Performance.now()")}} can provide more reliable and precise measurements of elapsed time than {{jsxref("Date.now()")}}.

Specifications

Specification Status Comment
{{SpecName('ESDraft', '#sec-date-objects', 'Date')}} {{Spec2('ESDraft')}}  
{{SpecName('ES6', '#sec-date-objects', 'Date')}} {{Spec2('ES6')}}  
{{SpecName('ES5.1', '#sec-15.9', 'Date')}} {{Spec2('ES5.1')}}  
{{SpecName('ES1')}} {{Spec2('ES1')}} Initial definition. Implemented in JavaScript 1.1.

Browser compatibility

{{CompatibilityTable}}
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support {{CompatVersionUnknown}} [1] {{CompatVersionUnknown}} [1] {{CompatVersionUnknown}} [2] {{CompatVersionUnknown}} [1] {{CompatVersionUnknown}} [1]
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}}

[1] Some browsers can have issues when parsing dates: 3/14/2012 blog from danvk Comparing FF/IE/Chrome on Parsing Date Strings

[2] ISO8601 Date Format is not supported in Internet Explorer 8, and other version can have issues when parsing dates

Revision Source

<div>{{JSRef}}</div>

<p>Creates a JavaScript <strong><code>Date</code></strong> instance that represents a single moment in time. <code>Date</code> objects are based on a time value that is the number of milliseconds since 1 January, 1970 UTC.</p>

<h2 id="Syntax">Syntax</h2>

<pre class="syntaxbox">
<code>new Date();
new Date(<var>value</var>);
new Date(<var>dateString</var>);
new Date(<var>year</var>, <var>month</var>[, <var>day</var>[, <var>hour</var>[, <var>minutes</var>[, <var>seconds</var>[, <var>milliseconds</var>]]]]]);
</code></pre>

<div class="note">
<p><strong>Note:</strong> JavaScript <code>Date</code> objects can only be instantiated by calling JavaScript <code>Date</code> as a constructor: calling it as a regular function (i.e. without the {{jsxref("Operators/new", "new")}} operator) will return a string rather than a <code>Date</code> object; unlike other JavaScript object types, JavaScript <code>Date</code> objects have no literal syntax.</p>
</div>

<h3 id="Parameters">Parameters</h3>

<div class="note">
<p><strong>Note:</strong> Where <code>Date</code> is called as a constructor with more than one argument, if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. <code>new Date(2013, 13, 1)</code> is equivalent to <code>new Date(2014, 1, 1)</code>, both create a date for <code>2014-02-01</code> (note that the month is 0-based). Similarly for other values: <code>new Date(2013, 2, 1, 0, 70)</code> is equivalent to <code>new Date(2013, 2, 1, 1, 10)</code> which both create a date for <code>2013-03-01T01:10:00</code>.</p>
</div>

<div class="note">
<p><strong>Note:</strong> Where <code>Date</code> is called as a constructor with more than one argument, the specifed arguments represent local time. If UTC is desired, use <code>new Date({{jsxref("Date.UTC()", "Date.UTC(...)")}})</code>&nbsp;with the same arguments.</p>
</div>

<dl>
 <dt><code>value</code></dt>
 <dd>Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC (Unix Epoch; but consider that most Unix time stamp functions count in seconds).</dd>
 <dt><code>dateString</code></dt>
 <dd>String value representing a date. The string should be in a format recognized by the {{jsxref("Date.parse()")}} method (<a href="https://tools.ietf.org/html/rfc2822#page-14">IETF-compliant RFC 2822 timestamps</a> and also a <a href="https://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15">version of ISO8601</a>).
 <div class="note">
 <p><strong>Note:</strong>&nbsp;parsing of date strings with the <code>Date</code> constructor (and <code>Date.parse</code>, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.</p>
 </div>
 </dd>
 <dt><code>year</code></dt>
 <dd>Integer value representing the year. Values from 0 to 99 map to the years 1900 to 1999. See the {{anch("Two_digit_years_map_to_1900_-_1999", "example below")}}.</dd>
 <dt><code>month</code></dt>
 <dd>Integer value representing the month, beginning with 0 for January to 11 for December.</dd>
 <dt><code>day</code></dt>
 <dd>Optional. Integer value representing the day of the month.</dd>
 <dt><code>hour</code></dt>
 <dd>Optional. Integer value representing the hour of the day.</dd>
 <dt><code>minute</code></dt>
 <dd>Optional. Integer value representing the minute segment of a time.</dd>
 <dt><code>second</code></dt>
 <dd>Optional. Integer value representing the second segment of a time.</dd>
 <dt><code>millisecond</code></dt>
 <dd>Optional. Integer value representing the millisecond segment of a time.</dd>
</dl>

<h2 id="Description">Description</h2>

<ul>
 <li>If no arguments are provided, the constructor creates a JavaScript <code>Date</code> object for the current date and time according to system settings.</li>
 <li>If at least two arguments are supplied, missing arguments are either set to 1 (if day is missing) or 0 for all others.</li>
 <li>The JavaScript date is based on a time value that is milliseconds since midnight 01 January, 1970 UTC. A day holds 86,400,000 milliseconds. The JavaScript <code>Date</code> object range is -100,000,000 days to 100,000,000 days relative to 01 January, 1970 UTC.</li>
 <li>The JavaScript <code>Date</code> object provides uniform behavior across platforms. The time value can be passed between systems to represent the same moment in time and if used to create a local date object, will reflect the local equivalent of the time.</li>
 <li>The JavaScript <code>Date</code> object supports a number of UTC (universal) methods, as well as local time methods. UTC, also known as Greenwich Mean Time (GMT), refers to the time as set by the World Time Standard. The local time is the time known to the computer where JavaScript is executed.</li>
 <li>Invoking JavaScript <code>Date</code> as a function (i.e., without the {{jsxref("Operators/new", "new")}} operator) will return a string representing the current date and time.</li>
</ul>

<h2 id="Properties">Properties</h2>

<dl>
 <dt>{{jsxref("Date.prototype")}}</dt>
 <dd>Allows the addition of properties to a JavaScript <code>Date</code> object.</dd>
 <dt><code>Date.length</code></dt>
 <dd>The value of <code>Date.length</code> is 7. This is the number of arguments handled by the constructor.</dd>
</dl>

<h2 id="Methods">Methods</h2>

<dl>
 <dt>{{jsxref("Date.now()")}}</dt>
 <dd>Returns the numeric value corresponding to the current time - the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.</dd>
 <dt>{{jsxref("Date.parse()")}}</dt>
 <dd>Parses a string representation of a date and returns the number of milliseconds since 1 January, 1970, 00:00:00, UTC.
 <div class="note">
 <p><strong>Note:</strong>&nbsp;Parsing of strings with <code>Date.parse</code> is strongly discouraged due to browser differences and inconsistencies.</p>
 </div>
 </dd>
 <dt>{{jsxref("Date.UTC()")}}</dt>
 <dd>Accepts the same parameters as the longest form of the constructor (i.e. 2 to 7) and returns the number of milliseconds since 1 January, 1970, 00:00:00 UTC.</dd>
</dl>

<h2 id="JavaScript_Date_instances">JavaScript <code>Date</code> instances</h2>

<p>All <code>Date</code> instances inherit from {{jsxref("Date.prototype")}}. The prototype object of the <code>Date</code> constructor can be modified to affect all <code>Date</code> instances.</p>

<h3 id="Date.prototype_Methods">Date.prototype Methods</h3>

<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/prototype', 'Methods')}}</div>

<h2 id="Examples">Examples</h2>

<h3 id="Several_ways_to_create_a_Date_object">Several ways to create a <code>Date</code> object</h3>

<p>The following examples show several ways to create JavaScript dates:</p>

<div class="note">
<p><strong>Note:</strong>&nbsp;parsing of date strings with the <code>Date</code> constructor (and <code>Date.parse</code>, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.</p>
</div>

<pre class="brush: js">
var today = new Date();
var birthday = new Date('December 17, 1995 03:24:00');
var birthday = new Date('1995-12-17T03:24:00');
var birthday = new Date(1995, 11, 17);
var birthday = new Date(1995, 11, 17, 3, 24, 0);
</pre>

<h3 id="Two_digit_years_map_to_1900_-_1999">Two digit years map to 1900 - 1999</h3>

<p>In order to create and get dates between the years 0 and 99 the {{jsxref("Date.prototype.setFullYear()")}} and {{jsxref("Date.prototype.getFullYear()")}} methods should be used.</p>

<pre class="brush: js">
var date = new Date(98, 1); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)

// Deprecated method, 98 maps to 1998 here as well
date.setYear(98);           // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)

date.setFullYear(98);       // Sat Feb 01 0098 00:00:00 GMT+0000 (BST)
</pre>

<h3 id="Calculating_elapsed_time">Calculating elapsed time</h3>

<p>The following examples show how to determine the elapsed time between two JavaScript dates in millisconds.</p>

<p>Due to the differing lengths of days (due to daylight saving changeover), months and years, expressing elapsed time in units greater than hours, minutes and seconds&nbsp;requires addressing a number of issues and should be thoroughly researched before being attempted.</p>

<pre class="brush: js">
// using Date objects
var start = Date.now();

// the event to time goes here:
doSomethingForALongTime();
var end = Date.now();
var elapsed = end - start; // elapsed time in milliseconds
</pre>

<pre class="brush: js">
// using built-in methods
var start = new Date();

// the event to time goes here:
doSomethingForALongTime();
var end = new Date();
var elapsed = end.getTime() - start.getTime(); // elapsed time in milliseconds
</pre>

<pre class="brush: js">
// to test a function and get back its return
function printElapsedTime(fTest) {
  var nStartTime = Date.now(),
      vReturn = fTest(),
      nEndTime = Date.now();

  console.log('Elapsed time: ' + String(nEndTime - nStartTime) + ' milliseconds');
  return vReturn;
}

yourFunctionReturn = printElapsedTime(yourFunction);
</pre>

<div class="note">
<p><strong>Note:</strong> In browsers that support the {{domxref("window.performance", "Web Performance API", "", 1)}}'s high-resolution time feature, {{domxref("Performance.now()")}} can provide more reliable and precise measurements of elapsed time than {{jsxref("Date.now()")}}.</p>
</div>

<h2 id="Specifications">Specifications</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-date-objects', 'Date')}}</td>
   <td>{{Spec2('ESDraft')}}</td>
   <td>&nbsp;</td>
  </tr>
  <tr>
   <td>{{SpecName('ES6', '#sec-date-objects', 'Date')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td>&nbsp;</td>
  </tr>
  <tr>
   <td>{{SpecName('ES5.1', '#sec-15.9', 'Date')}}</td>
   <td>{{Spec2('ES5.1')}}</td>
   <td>&nbsp;</td>
  </tr>
  <tr>
   <td>{{SpecName('ES1')}}</td>
   <td>{{Spec2('ES1')}}</td>
   <td>Initial definition. Implemented in JavaScript 1.1.</td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>

<div>{{CompatibilityTable}}</div>

<div id="compat-desktop">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Chrome</th>
   <th>Firefox (Gecko)</th>
   <th>Internet Explorer</th>
   <th>Opera</th>
   <th>Safari</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatVersionUnknown}} [1]</td>
   <td>{{CompatVersionUnknown}} [1]</td>
   <td>{{CompatVersionUnknown}} [2]</td>
   <td>{{CompatVersionUnknown}} [1]</td>
   <td>{{CompatVersionUnknown}} [1]</td>
  </tr>
 </tbody>
</table>
</div>

<div id="compat-mobile">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Android</th>
   <th>Chrome for Android</th>
   <th>Firefox Mobile (Gecko)</th>
   <th>IE Mobile</th>
   <th>Opera Mobile</th>
   <th>Safari Mobile</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
  </tr>
 </tbody>
</table>
</div>

<p>[1] Some browsers can have issues when parsing dates:&nbsp;<a href="https://dygraphs.com/date-formats.html">3/14/2012 blog from danvk Comparing FF/IE/Chrome on Parsing Date Strings</a></p>

<p>[2] <a href="https://msdn.microsoft.com/en-us//library/ie/ff743760(v=vs.94).aspx">ISO8601 Date Format is not supported</a> in Internet Explorer 8, and other version can have <a href="https://dygraphs.com/date-formats.html">issues when parsing dates</a></p>
Revert to this revision