|
1 | | -# About |
| 1 | +# Introduction |
2 | 2 |
|
3 | 3 | JavaScript has a built-in object `Date` which stores date and time, and provides methods for their management. |
4 | 4 |
|
| 5 | +<!-- prettier-ignore --> |
| 6 | +~~~exercism/caution |
| 7 | +It was based on Java's `java.util.Date` class, which was replaced in the early 2010s, but for backwards compatibility, JavaScript's `Date` sticks around. |
| 8 | +
|
| 9 | +Because of how hard it is to work with Dates in general and because of how bad or non-existing timezone handling is, many libraries exist such as `moment.js`, `day.js`, `date-fns` and `luxon`. |
| 10 | +None of these are available on Exercism. |
| 11 | +
|
| 12 | +In your own projects, do not use a deprecated / unmaintained package such as `moment.js` but rely on more modern alternatives like `luxon`, or the not yet widely available [Temporal][mdn-temporal]. |
| 13 | +This exercise focusses on `Date`, which will remain relevant until the end of JavaScript. |
| 14 | +~~~ |
| 15 | + |
5 | 16 | ## Creation |
6 | 17 |
|
7 | | -A `Date` object in an instance of the `Date` class. It can be created without passing any arguments to the constructor function. This results in a `Date` object that represents the current date and time: |
| 18 | +A `Date` object in an instance of the `Date` class. |
| 19 | +It can be created without passing any arguments to the constructor function. |
| 20 | +This results in a `Date` object that represents the current date and time: |
8 | 21 |
|
9 | 22 | ```javascript |
10 | 23 | const now = new Date(); |
11 | 24 | // => Thu Apr 14 2022 11:46:08 GMT+0530 (India Standard Time) |
12 | | - |
13 | | -// Shows current day, date and time in your time zone. |
| 25 | +// Shows current day, date and time (in your time zone). |
14 | 26 | ``` |
15 | 27 |
|
16 | | -However, different types of arguments can also be used to create date object, as follows: |
17 | | - |
18 | | -### Timestamp value |
19 | | - |
20 | | -> A timestamp is an integer number representing the number of **milliseconds** that has passed since **Jan 1st of 1970 [UTC][utc-defn]+0**, however, _with reference to your local time zone._ |
21 | | -> This can be used as an argument for the Date object. |
22 | | -> |
23 | | -> ```javascript |
24 | | -> const Jan01_1970 = new Date(0); |
25 | | -> // 0 means 01.01.1970 UTC+0 |
26 | | -> |
27 | | -> const Jan02_1970 = new Date(24 * 3600 * 1000); |
28 | | -> // adding 24 hours, we get 02.01.1970 UTC+0 |
29 | | -> |
30 | | -> // Note that the objects created here would show the corresponding time in your time zone. |
31 | | -> ``` |
32 | | -> |
33 | | -> [^1] |
34 | | -
|
35 | | -<!-- prettier-ignore-start --> |
36 | | -~~~~exercism/note |
37 | | -> January 1st, 1970 at 00:00:00 UTC is referred to as the Unix epoch. |
38 | | -> Unix is an operating system originally developed in the 1960s. |
39 | | -> Early Unix engineers picked that date arbitrarily because they needed to set a uniform date for the start of time, and > New Year's Day, 1970, seemed most convenient. [^2] |
40 | | -~~~~ |
41 | | -<!-- prettier-ignore-end --> |
42 | | -
|
43 | | -### Timestamp string |
44 | | -
|
45 | | -You can pass a string value representing a date to the `Date` constructor. |
46 | | -The string needs to follow a format that is recognized by the `Date.parse()` method. |
47 | | -You will learn more about this below. |
48 | | -
|
49 | | -### Date object |
50 | | -
|
51 | | -An existing date object can also be used as an argument. |
52 | | -This makes a copy of the existing `Date` object with the same date and time. |
53 | | -
|
54 | | -```javascript |
55 | | -const t1 = new Date(); |
56 | | -const t2 = new Date(t1); |
57 | | -
|
58 | | -// Values of t1 and t2 will be the same. |
59 | | -``` |
| 28 | +### Unix timestamp (number) |
60 | 29 |
|
61 | | -### Individual date and time component values |
62 | | - |
63 | | -> Given at least a year and month, this form of `Date()` returns a `Date` object whose component values _(year, month, day, hour, minute, second, and millisecond)_ all come from the following parameters. |
64 | | -> Any missing fields are given the lowest possible value (1 for day and 0 for every other component). |
65 | | -> The parameter values are all evaluated against the _local time zone, rather than UTC_. |
66 | | -> |
67 | | -> - `year`: Integer values from 0 to 99 map to the years 1900 to 1999. |
68 | | -> All other values are the actual year. |
69 | | -> - `monthIndex`: Integer value representing the month, beginning with _0 for January to 11 for December_. |
70 | | -> If a value greater than 11 is passed in, then those months will be added to the date. |
71 | | -> For example, new Date(1990, 12, 1) will return January 1st, 1991. |
72 | | -> - `day` (Optional): Integer value representing the day of the month. |
73 | | -> The default is 1. |
74 | | -> - `hours` (Optional): Integer value between 0 and 23 representing the hour of the day. |
75 | | -> Defaults to 0. |
76 | | -> - `minutes` (Optional): Integer value representing the minute segment of a time. |
77 | | -> The default is 0 minutes past the hour. |
78 | | -> - `seconds` (Optional): Integer value representing the second segment of a time. |
79 | | -> The default is 0 seconds past the minute. |
80 | | -> - `milliseconds` (Optional): Integer value representing the millisecond segment of a time. |
81 | | -> The default is 0 milliseconds past the second. |
82 | | -> |
83 | | -> [^3] |
| 30 | +If a number is passed in, this will be interpreted as a `timestamp`. |
| 31 | +A timestamp is an integer number representing the number of **milliseconds** that has passed since **1 January 1970 [UTC][defn-utc]+0**. |
84 | 32 |
|
85 | 33 | ```javascript |
86 | | -const date1 = new Date(95, 11, 17); |
87 | | -// Creates Date for Dec 17 1995 00:00 if your local timezone is equivalent to UTC. |
| 34 | +const epoch = new Date(0); |
| 35 | +// Thu Jan 01 1970 01:00:00 GMT+0100 (Central European Standard Time) |
88 | 36 |
|
89 | | -const date2 = new Date(2013, 12, 5, 13, 24, 0); |
90 | | -// Creates Date for Jan 5 2014 13:24 if your local timezone is equivalent to UTC. |
| 37 | +const another = new Date(1749508766627); |
| 38 | +// Tue Jun 10 2025 00:39:26 GMT+0200 (Central European Summer Time) |
91 | 39 | ``` |
92 | 40 |
|
93 | | -## `Date.parse()` |
94 | | - |
95 | | -`Date.parse()` takes **string as a input and returns a timestamp** (number of milliseconds from 1 Jan 1970 UTC+0), provided the string is in the format YYYY-MM-DDTHH:mm:ss.sssZ, where: |
| 41 | +One may expect `new Date(0)` to generate the "earliest" date object, but JavaScript will convert the date to your local timezone, which means that only those around [GMT / with an UTC+0][defn-gmt] timezone will actually get the [Unix epoch][defn-unix-epoch] value. |
96 | 42 |
|
97 | | -> - `YYYY-MM-DD` - is the date: year-month-day. |
98 | | -> - `T` - The character "T" is used as the delimiter |
99 | | -> - `HH:mm:ss.sss` - is the time: hours, minutes, seconds and milliseconds. |
100 | | -> - `Z` - This _optional_ part denotes the time zone. |
101 | | -> If `Z` is present, the `Date` will be set to UTC. |
102 | | -> If `Z` is not present, it will be Local Time. |
103 | | -> |
104 | | -> If the format is invalid, `NaN` is returned. [^4] |
| 43 | +### ISO 8601 timestamp (string) |
105 | 44 |
|
106 | | -Shorter variants are also possible, like `YYYY-MM-DD` or `YYYY-MM` or even `YYYY`. However, note that these variants **set the `Date` to UTC**, even though `Z` not mentioned. |
107 | | -To understand what exactly happens check out [this section][mdn-diff-assumed-timezone] of a MDN page. |
108 | | - |
109 | | -```javascript |
110 | | -const d1 = Date.parse('2019-01-01'); |
111 | | -const d2 = Date.parse('2019-01-01T00:00:00.000Z'); |
| 45 | +You can pass a string value representing a date to the `Date` constructor. |
| 46 | +The **only** format that is consistent across implementations is the [simplified version][mdn-date-string-format] of the internationally recognized and standardized so-called [ISO 8601 timestamp strings][defn-iso8601]. |
112 | 47 |
|
113 | | -// Both d1 and d2 are of value 1546300800000, as times are set to UTC. |
| 48 | +A moment in time at [UTC][defn-gmt] looks like this: |
114 | 49 |
|
115 | | -const d3 = Date.parse('2019-01-01T00:00:00.000'); |
116 | | -// This would have a different value (unless you live in GMT) as |
117 | | -// it is set to your local time zone. |
| 50 | +```text |
| 51 | +YYYY-MM-DDTHH:MM:SSZ |
| 52 | +YYYYMMDDTHHMMSSZ |
118 | 53 | ``` |
119 | 54 |
|
120 | | -<!-- prettier-ignore-start --> |
121 | | -~~~~exercism/caution |
122 | | -The use of `Date.parse()` (and the timestamp string method which works similarly) is strongly discouraged due to browser differences and inconsistencies. [^5] |
123 | | -~~~~ |
124 | | -<!-- prettier-ignore-end --> |
| 55 | +Where the following substitutions take place: |
125 | 56 |
|
126 | | -## Accessing `Date` components |
| 57 | +| Key | Description | |
| 58 | +| ---- | ------------------------------------------- | |
| 59 | +| YYYY | The calendar year, represented in 4 digits | |
| 60 | +| MM | The calendar month, represented in 2 digits | |
| 61 | +| DD | The calendar day, represented in 2 digits | |
| 62 | +| HH | The hours in a 24-hour clock, 2 digits | |
| 63 | +| MM | The minutes, 2 digits | |
| 64 | +| SS | The seconds, 2 digits | |
127 | 65 |
|
128 | | -The following are the methods to access the year, month and so on from the Date object: |
| 66 | +The letter `T` separates the date from the time. |
| 67 | +The letter `Z` indicates UTC (no timezone, no Day Light Savings). |
129 | 68 |
|
130 | | -> - `getFullYear()`- Get the year (4 digits) |
131 | | -> - `getMonth()`- Get the month, from 0 to 11. |
132 | | -> - `getDate()`- Get the day of month, from 1 to 31. |
133 | | -> - `getHours()`, `getMinutes()`, `getSeconds()`, `getMilliseconds()`- Get the corresponding time components. |
134 | | -> - `getDay()`- Get the day of week, from 0 (Sunday) to 6 (Saturday). |
135 | | -> - `getTime()`- Get the number of milliseconds passed since 01.01.1970 UTC. |
136 | | -> |
137 | | -> [^6] |
| 69 | +<!-- prettier-ignore --> |
| 70 | +~~~exercism/caution |
| 71 | +Other formats that are accepted by `Date.parse` may or may not work. |
| 72 | +When working with Dates in JavaScript, _always_ use an ISO 8601 timestamp when converting from a `string` to a `Date`. |
138 | 73 |
|
139 | | -```javascript |
140 | | -const date0 = new Date(0); //Jan 1 1970 00:00:00 |
141 | | -let month = date0.getMonth()); // => 0; as Jan is the month |
142 | | -let date = date0.getDay(); // Find out which day the new year of 1970 was! |
| 74 | +Date-only forms are allowed, but not all ISO 8601 formats are supported. |
| 75 | +Consult the [simplified version explanation page on MDN][mdn-date-string-format]. |
| 76 | +~~~ |
143 | 77 |
|
144 | | -const date1 = new Date(2020, 11, 13, 5); // Dec 13 2020 5:00:00 |
145 | | -let millsecs = date1.getTime(); // find out how many have milliseconds passed since Jan 1 1890! |
146 | | -``` |
| 78 | +If the timestamp does not end in `Z`, and it does not end with `+HH:MM` or `-HH:MM`, indicating a timezone offset, because of historical reasons, the following applies: |
147 | 79 |
|
148 | | -<!-- prettier-ignore-start --> |
149 | | -~~~~exercism/caution |
150 | | -Many JavaScript engines implement a non-standard method `getYear()`. |
151 | | -**This method is deprecated.** |
152 | | -It returns a 2-digit year sometimes. |
153 | | -Hence, `getFullYear()` must always be used instead. |
154 | | -~~~~ |
155 | | -<!-- prettier-ignore-end --> |
156 | | - |
157 | | -## Modifying `Date` components |
158 | | - |
159 | | -The following methods allow to modify date/time components : |
160 | | - |
161 | | -> - `setFullYear(year, [month], [date])` |
162 | | -> - `setMonth(month, [date])` |
163 | | -> - `setDate(date)` |
164 | | -> - `setHours(hour, [min], [sec], [ms])` |
165 | | -> - `setMinutes(min, [sec], [ms])` |
166 | | -> - `setSeconds(sec, [ms])` |
167 | | -> - `setMilliseconds(ms)` |
168 | | -> - `setTime(timestamp)` (sets the whole date by milliseconds since 01.01.1970 UTC) |
169 | | -> |
170 | | -> Parameters in `[]` above are _optional_. |
171 | | -> If not mentioned, the components are not modified. |
172 | | -> Every one of them except `setTime()` has a UTC-variant, for instance: `setUTCHours()`. [^7] |
| 80 | +> When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as a local time. |
| 81 | +> The interpretation as a UTC time is due to a historical spec error that was not consistent with ISO 8601 but could not be changed due to web compatibility. |
| 82 | +> See [Broken Parser – A Web Reality Issue][ref-broken-parser]. |
173 | 83 |
|
174 | | -```javascript |
175 | | -let today = new Date(); |
| 84 | +### Date object |
176 | 85 |
|
177 | | -today.setHours(0); // still today, but only the hour is changed to 0 |
| 86 | +An existing date object can also be used as a constructor argument. |
| 87 | +This makes a copy of the existing `Date` object with the same date and time. |
178 | 88 |
|
179 | | -today.setHours(0, 0, 0, 0); // still today, now sharply 00:00:00 |
| 89 | +```javascript |
| 90 | +const t1 = new Date(); |
| 91 | +const t2 = new Date(t1); |
| 92 | +// Values of t1 and t2 will be the same. |
180 | 93 | ``` |
181 | 94 |
|
182 | | -## Calculating Time Difference and `Date.now()` |
| 95 | +### Supplying individual date and time component values |
183 | 96 |
|
184 | | -To measure the time elapsed between two given dates, we can use the `Date.getTime()` method. |
| 97 | +A date representing a date can be created by passing three numbers. |
| 98 | +A date representing a date and time can be created by passing in 6 numbers. |
185 | 99 |
|
186 | 100 | ```javascript |
187 | | -const d1 = new Date(2021, 12, 11, 5, 13, 32, 21); |
188 | | -const d2 = new Date(2021, 12, 23, 4, 12, 55); |
| 101 | +const date1 = new Date(95, 11, 17); |
| 102 | +// Creates Date for Dec 17 1995 00:00 if your local timezone is equivalent to UTC. |
189 | 103 |
|
190 | | -let timeElapsed = d2.getTime() - d1.getTime(); // => 1033162979 |
| 104 | +const date2 = new Date(2013, 12, 5, 13, 24, 0); |
| 105 | +// Creates Date for Jan 5 2014 13:24 if your local timezone is equivalent to UTC. |
191 | 106 | ``` |
192 | 107 |
|
193 | | -Moreover, if we wish to measure the time taken on a live basis, for example the time taken for execution for program, we could use `Date.now()` which provides the timestamp of current time. |
| 108 | +The second value is the `month`, which starts at `0` for January, up to `11` for December. |
194 | 109 |
|
195 | | -> As you might notice, this is semantically equivalent to `new Date().getTime()`, but it doesn’t create an intermediate `Date` object. |
196 | | -> Hence, it makes the code more efficient. [^8] |
| 110 | +## `Date.parse()` |
197 | 111 |
|
198 | | -```javascript |
199 | | -const start = Date.now(); // milliseconds count from 1 Jan 1970 |
| 112 | +You may find mentions of or references to a date parsing function `Date.parse`. |
| 113 | +Because there are only a few invariants (truths) for this function and because the rest of the implementation is not specified (and thus not standard), one should not use it. |
200 | 114 |
|
201 | | -// execute a task |
202 | | -for (let i = 0; i < 100000; i++) { |
203 | | - let task = i * i * i * i; |
204 | | -} |
| 115 | +## Accessing `Date` components |
205 | 116 |
|
206 | | -const end = Date.now(); // done |
| 117 | +There are various methods on date objects that return the components of the date: |
207 | 118 |
|
208 | | -let duration = end - start; |
209 | | -// how long it took to run the loop, in seconds |
| 119 | +```javascript |
| 120 | +getFullYear(); // Get the year (4 digits) |
| 121 | +getMonth(); // Get the month, from 0 to 11. |
| 122 | +getDate(); // Get the day of month, from 1 to 31. |
| 123 | +getHours(); // Get the hour in a 24 clock, from 0 to 23 |
| 124 | +getMinutes(); // Get the minutes, from 0 to 59 |
| 125 | +getSeconds(); // Get the seconds, from 0 to 59 |
| 126 | +getMilliseconds(); // Get the milliseconds, from 0 and 999 |
| 127 | +getDay(); // Get the day of week, from 0 (Sunday) to 6 (Saturday). |
210 | 128 | ``` |
211 | 129 |
|
212 | | -## Comparing Dates |
213 | | - |
214 | | -We can use `<` and `>` operators to compare two `Date` objects, the date occuring _later being treated as greater_. |
215 | | - |
216 | | -The `==` or `===` do not work with `Date`, and output `false` in any case, even if dates are equal. |
217 | | -However, we could use the `Date.getTime()` method to obtain the timestamps (which is of the data type `number`) and compare them using equality operators. |
| 130 | +Each of these has an applicable `set` variant (e.g. `setFullYear`) to update the value. |
| 131 | +Any overflowing value rolls over to the next component: |
218 | 132 |
|
219 | 133 | ```javascript |
220 | | -const d1 = new Date(2021, 12, 11); |
221 | | -const d2 = new Date(1990, 11, 23); |
| 134 | +const date = new Date('2025-02-28T12:42:00Z'); |
| 135 | +// => Fri Feb 28 2025 13:42:00 GMT+0100 (Central European Standard Time) |
222 | 136 |
|
223 | | -d1 > d2; // true |
| 137 | +date.setDate(29); |
| 138 | +// there was no February 29th in 2025. |
224 | 139 |
|
225 | | -const d1Copy = new Date(d1); // d1Copy will be same as d1 |
| 140 | +date.getDate(); |
| 141 | +// => 1 |
226 | 142 |
|
227 | | -d1Copy === d1; // false, even though they are same |
228 | | -d1Copy.getTime() === d1.getTime(); //true |
| 143 | +date.toString(); |
| 144 | +// => Sat Mar 01 2025 13:42:00 GMT+0100 (Central European Standard Time) |
229 | 145 | ``` |
230 | 146 |
|
231 | | -[^1]: https://javascript.info/date |
232 | | - |
233 | | -[^2]: https://kb.narrative.io/what-is-unix-time |
234 | | - |
235 | | -[^3]: https://javascript.info/date#setting-date-components |
| 147 | +There are UTC variants for all the methods that disregard the local timezone. |
236 | 148 |
|
237 | | -[^4]: https://javascript.info/date#date-parse-from-a-string |
| 149 | +## Converting from date |
238 | 150 |
|
239 | | -[^5]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date#several_ways_to_create_a_date_object |
| 151 | +Date objects have a method `getTime()` that returns the UNIX timestamp in milliseconds, ie. amount of milliseconds the midnight at the beginning of January 1, 1970, UTC. |
| 152 | +Additionally, a method `toISOString()` is available to convert from a date object to a ISO 8601 timestamp string. |
240 | 153 |
|
241 | | -[^6]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date#several_ways_to_create_a_date_object |
242 | | - |
243 | | -[^7]: https://javascript.info/date#access-date-components |
244 | | - |
245 | | -[^8]: https://javascript.info/date#date-now |
| 154 | +## Comparing Dates |
246 | 155 |
|
247 | | -[utc-defn]: https://simple.wikipedia.org/wiki/Coordinated_Universal_Time |
248 | | -[mdn-diff-assumed-timezone]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#differences_in_assumed_time_zone |
| 156 | +Greater than (`>`) and greater than or equals (`>=`) as well as less than (`<`) and less than or equals (`<=`) can be used directly between two dates or a date and a number. |
| 157 | +This works because JavaScript will try to coerce the date to a primitive. |
| 158 | + |
| 159 | +<!-- prettier-ignore --> |
| 160 | +~~~@exercism/advanced |
| 161 | +When doing a comparison between two dates or date and a number, JavaScript calls [`[Symbol.toPrimitive]("number")`][mdn-to-primitive] which internally calls [`date.valueOf()`][mdn-date-value-of]. |
| 162 | +The latter is the same as calling [`date.getTime()`][mdn-date-get-time]. |
| 163 | +
|
| 164 | +If you do not want to rely on this behaviour, convert to a number using `getTime()` first. |
| 165 | +~~~ |
| 166 | + |
| 167 | +Dates cannot be compared using equality (`==`, and `===`), but the result of `.getTime()` can. |
| 168 | + |
| 169 | +[defn-utc]: https://simple.wikipedia.org/wiki/Coordinated_Universal_Time |
| 170 | +[defn-gmt]: https://simple.wikipedia.org/wiki/Greenwich_Mean_Time |
| 171 | +[defn-unix-epoch]: https://en.wikipedia.org/wiki/Epoch_%28computing%29 |
| 172 | +[defn-iso8601]: https://en.wikipedia.org/wiki/ISO_8601 |
| 173 | +[mdn-temporal]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal |
| 174 | +[mdn-date-string-format]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_time_string_format |
| 175 | +[mdn-to-primitive]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Symbol.toPrimitive |
| 176 | +[mdn-date-value-of]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/valueOf |
| 177 | +[mdn-date-get-time]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime |
| 178 | +[ref-broken-parser]: https://maggiepint.com/2017/04/11/fixing-javascript-date-web-compatibility-and-reality/ |
0 commit comments