1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
|
---
title: Date
slug: Web/JavaScript/Reference/Global_Objects/Date
tags:
- Date
- Epoch
- JavaScript
- NeedsTranslation
- Time
- TopicStub
- Unix Epoch
- timeStamp
translation_of: Web/JavaScript/Reference/Global_Objects/Date
---
<div>{{JSRef}}</div>
<p><span class="seoSummary">Creates a JavaScript <strong><code>Date</code></strong> instance that represents a single moment in time in a platform-independent format.</span> <code>Date</code> objects use a <a href="http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_16">Unix Time Stamp</a>, an integer value that is the number of milliseconds since 1 January 1970 UTC.</p>
<div>{{EmbedInteractiveExample("pages/js/date-constructor.html")}}</div>
<h2 id="Instantiating_Date_objects">Instantiating Date objects</h2>
<p>The only way to create a new JavaScript <code>Date</code> object is to use the {{jsxref("new")}} operator:</p>
<pre class="brush: js">let now = new Date();</pre>
<p>If you simply call the {{jsxref("Date", "Date()")}} object directly, the returned value is a string instead of a <code>Date</code> object. There's no <code>Date</code> literal syntax in JavaScript.</p>
<h2 id="Syntax">Syntax</h2>
<pre class="syntaxbox">new Date();
new Date(<var>value</var>);
new Date(<var>dateString</var>);
new Date(<var>year</var>, <var>monthIndex</var> [, <var>day</var> [, <var>hours</var> [, <var>minutes</var> [, <var>seconds</var> [, <var>milliseconds</var>]]]]]);
</pre>
<h3 id="Parameters">Parameters</h3>
<p>There are four basic forms for the <code>Date()</code> constructor:</p>
<h4 id="No_parameters">No parameters</h4>
<p>When no parameters are provided, the newly-created <code>Date</code> object represents the current date and time, specified in the local time zone, as of the time of instantiation.</p>
<h4 id="Unix_timestamp">Unix timestamp</h4>
<dl>
<dt><code>value</code></dt>
<dd>A <a href="http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_16">Unix Time Stamp</a> which is an integer value representing the number of milliseconds since January 1, 1970, 00:00:00 UTC (the Unix epoch), with leap seconds ignored. Keep in mind that most Unix timestamp functions are only accurate to the nearest second.</dd>
</dl>
<h4 id="Timestamp_string">Timestamp string</h4>
<dl>
<dt><code>dateString</code></dt>
<dd>A string value representing a date, specified in a format recognized by the {{jsxref("Date.parse()")}} method (these formats are <a href="http://tools.ietf.org/html/rfc2822#page-14">IETF-compliant RFC 2822 timestamps</a> and also strings in a <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15">version of ISO8601</a>).
<div class="note">
<p><strong>Note:</strong> 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. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.</p>
</div>
</dd>
</dl>
<h4 id="Individual_date_and_time_component_values">Individual date and time component values</h4>
<p>Given at least a year and month, this form of <code>Date()</code> returns a <code>Date</code> object whose component values (year, month, day, hour, minute, second, and millisecond) all come from the following parameters. Any missing fields are given the lowest possible value (1 for the <code>day</code> and 0 for every other component).</p>
<dl>
<dt><code>year</code></dt>
<dd>Integer value representing the year. Values from 0 to 99 map to the years 1900 to 1999; all other values are the actual year. See the {{anch("Two_digit_years_map_to_1900_-_1999", "example below")}}.</dd>
<dt><code>monthIndex</code></dt>
<dd>Integer value representing the month, beginning with 0 for January to 11 for December.</dd>
<dt><code>day</code> {{optional_inline}}</dt>
<dd>Integer value representing the day of the month. If not specified, the default value of 1 is used.</dd>
<dt><code>hours</code> {{optional_inline}}</dt>
<dd>Integer value representing the hour of the day. The default is 0 (midnight).</dd>
<dt><code>minutes</code> {{optional_inline}}</dt>
<dd>Integer value representing the minute segment of a time. The default is 0 minutes past the hour.</dd>
<dt><code>seconds</code> {{optional_inline}}</dt>
<dd>Integer value representing the second segment of a time. The default is zero seconds past the minute.</dd>
<dt><code>milliseconds</code> {{optional_inline}}</dt>
<dd>Integer value representing the millisecond segment of a time. The default is 0 milliseconds past the second.</dd>
</dl>
<h2 id="User_notes">User notes</h2>
<h3 id="The_Unix_epoch_and_timestamps">The Unix epoch and timestamps</h3>
<p>A JavaScript date is fundamentally specified as the number of milliseconds that have elapsed since midnight on January 1, 1970, UTC. This date and time is called the <strong>Unix epoch</strong>, which is the predominant base value for computer-recorded date and time values.</p>
<div class="blockIndicator note">
<p><strong>Note:</strong> It's important to keep in mind that the date and time is stored in the local time zone, and that the basic methods to fetch the date and time or its components all work in the local time zone as well.</p>
</div>
<p>A day is made up of 86,400,000 milliseconds. Given that and the size of the underlying number used to record the timestamp, and it can be calculated that the <code>Date</code> object can represent dates within ±100,000,000 (one hundred million) days relative to January 1, 1970 UTC. That means that in the year <span class="qv3Wpe" id="cwos">293,742</span>, we'll have to think about fixing this.</p>
<h3 id="Date_format_and_time_zone_conversions">Date format and time zone conversions</h3>
<p>There are a number of methods available to obtain the date in various formats, as well as to do time zone conversions. Especially useful are the functions that output the date and time in Coordinated Universal Time (UTC), the global standard time defined by the World Time Standard. This time is historically known as Greenwich Mean Time, as UTC lies along the meridian that includes London and nearby Greenwhich in the United Kingdom. The user's device provides the local time.</p>
<p>In addition to methods to read and alter individual components of the local date and time, such as {{jsxref("Date.getDay", "getDay()")}} and {{jsxref("Date.setHours", "setHours()")}}, there are also versions of the same methods that read and maniuplate the date and time using UTC, such as {{jsxref("Date.getUTCDay()", "getUTCDay()")}} and {{jsxref("Date.setHoursUTC", "setUTCHours()")}}.</p>
<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. It's not generally a useful result.</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 January 1, 1970 00:00:00 UTC, with leap seconds ignored.</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, with leap seconds ignored.
<div class="note">
<p><strong>Note:</strong> 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 January 1, 1970, 00:00:00 UTC, with leap seconds ignored.</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> 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 milliseconds.</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 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;
}
var 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>
<h3 id="Get_the_number_of_seconds_since_Unix_Epoch">Get the number of seconds since Unix Epoch</h3>
<pre class="brush: js">var seconds = Math.floor(Date.now() / 1000);
</pre>
<p>In this case it's important to return only an integer (so a simple division won't do), and also to only return actually elapsed seconds (that's why this code uses {{jsxref("Math.floor()")}} and not {{jsxref("Math.round()")}}).</p>
<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> </td>
</tr>
<tr>
<td>{{SpecName('ES6', '#sec-date-objects', 'Date')}}</td>
<td>{{Spec2('ES6')}}</td>
<td> </td>
</tr>
<tr>
<td>{{SpecName('ES5.1', '#sec-15.9', 'Date')}}</td>
<td>{{Spec2('ES5.1')}}</td>
<td> </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>
<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p>
<p>{{Compat("javascript.builtins.Date", 3)}}</p>
|