|
| 1 | +# Introduction |
| 2 | + |
| 3 | +JavaScript has a built-in object `Date` which stores date and time, and provides methods for their management. |
| 4 | + |
| 5 | +## Creation |
| 6 | + |
| 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: |
| 8 | + |
| 9 | +```javascript |
| 10 | +const now = new Date(); |
| 11 | +// => Thu Apr 14 2022 11:46:08 GMT+0530 (India Standard Time) |
| 12 | + |
| 13 | +// Shows current day, date and time in your time zone. |
| 14 | +``` |
| 15 | + |
| 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 | +### Timestamp string |
| 36 | +
|
| 37 | +You can pass a string value representing a date to the `Date` constructor. |
| 38 | +The string needs to follow a format that is recognized by the `Date.parse()` method. |
| 39 | +You will learn more about this below. |
| 40 | +
|
| 41 | +### Date object |
| 42 | +
|
| 43 | +An existing date object can also be used as an argument. |
| 44 | +This makes a copy of the existing `Date` object with the same date and time. |
| 45 | +
|
| 46 | +```javascript |
| 47 | +const t1 = new Date(); |
| 48 | +const t2 = new Date(t1); |
| 49 | +
|
| 50 | +// Values of t1 and t2 will be the same. |
| 51 | +``` |
| 52 | +
|
| 53 | +### Individual date and time component values |
| 54 | + |
| 55 | +> 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. |
| 56 | +> Any missing fields are given the lowest possible value (1 for day and 0 for every other component). |
| 57 | +> The parameter values are all evaluated against the _local time zone, rather than UTC_. |
| 58 | +> |
| 59 | +> - `year`: Integer values from 0 to 99 map to the years 1900 to 1999. |
| 60 | +> All other values are the actual year. |
| 61 | +> - `monthIndex`: Integer value representing the month, beginning with _0 for January to 11 for December_. |
| 62 | +> If a value greater than 11 is passed in, then those months will be added to the date. |
| 63 | +> For example, new Date(1990, 12, 1) will return January 1st, 1991. |
| 64 | +> - `day` (Optional): Integer value representing the day of the month. |
| 65 | +> The default is 1. |
| 66 | +> - `hours` (Optional): Integer value between 0 and 23 representing the hour of the day. |
| 67 | +> Defaults to 0. |
| 68 | +> - `minutes` (Optional): Integer value representing the minute segment of a time. |
| 69 | +> The default is 0 minutes past the hour. |
| 70 | +> - `seconds` (Optional): Integer value representing the second segment of a time. |
| 71 | +> The default is 0 seconds past the minute. |
| 72 | +> - `milliseconds` (Optional): Integer value representing the millisecond segment of a time. |
| 73 | +> The default is 0 milliseconds past the second. |
| 74 | +> |
| 75 | +> [^2] |
| 76 | +
|
| 77 | +```javascript |
| 78 | +const date1 = new Date(95, 11, 17); |
| 79 | +// Creates Date for Dec 17 1995 00:00 if your local timezone is equivalent to UTC. |
| 80 | + |
| 81 | +const date2 = new Date(2013, 12, 5, 13, 24, 0); |
| 82 | +// Creates Date for Jan 5 2014 13:24 if your local timezone is equivalent to UTC. |
| 83 | +``` |
| 84 | + |
| 85 | +## `Date.parse()` |
| 86 | + |
| 87 | +`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: |
| 88 | + |
| 89 | +> - `YYYY-MM-DD` - is the date: year-month-day. |
| 90 | +> - `T` - The character "T" is used as the delimiter |
| 91 | +> - `HH:mm:ss.sss` - is the time: hours, minutes, seconds and milliseconds. |
| 92 | +> - `Z` - This _optional_ part denotes the time zone. |
| 93 | +> If `Z` is present, the `Date` will be set to UTC. |
| 94 | +> If `Z` is not present, it will be Local Time. |
| 95 | +> |
| 96 | +> If the format is invalid, `NaN` is returned. [^3] |
| 97 | +
|
| 98 | +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. |
| 99 | +To understand what exactly happens check out [this section][mdn-diff-assumed-timezone] of a MDN page. |
| 100 | + |
| 101 | +```exercism/caution |
| 102 | +The use of `Date.parse()` (and the timestamp string method which works similarly) is strongly discouraged due to browser differences and inconsistencies. [^4] |
| 103 | +``` |
| 104 | + |
| 105 | +## Accessing `Date` components |
| 106 | + |
| 107 | +The following are the methods to access the year, month and so on from the Date object: |
| 108 | + |
| 109 | +> - `getFullYear()`- Get the year (4 digits) |
| 110 | +> - `getMonth()`- Get the month, from 0 to 11. |
| 111 | +> - `getDate()`- Get the day of month, from 1 to 31. |
| 112 | +> - `getHours()`, `getMinutes()`, `getSeconds()`, `getMilliseconds()`- Get the corresponding time components. |
| 113 | +> - `getDay()`- Get the day of week, from 0 (Sunday) to 6 (Saturday). |
| 114 | +> - `getTime()`- Get the number of milliseconds passed since 01.01.1970 UTC. |
| 115 | +> |
| 116 | +> [^5] |
| 117 | +
|
| 118 | +```javascript |
| 119 | +const date0 = new Date(0); //Jan 1 1970 00:00:00 |
| 120 | +let month = date0.getMonth()); // => 0; as Jan is the month |
| 121 | +let date = date0.getDay(); // Find out which day the new year of 1970 was! |
| 122 | + |
| 123 | +const date1 = new Date(2020, 11, 13, 5); // Dec 13 2020 5:00:00 |
| 124 | +let millsecs = date1.getTime(); // find out how many have milliseconds passed since Jan 1 1890! |
| 125 | +``` |
| 126 | + |
| 127 | +## Modifying `Date` components |
| 128 | + |
| 129 | +The following methods allow to modify date/time components : |
| 130 | + |
| 131 | +> - `setFullYear(year, [month], [date])` |
| 132 | +> - `setMonth(month, [date])` |
| 133 | +> - `setDate(date)` |
| 134 | +> - `setHours(hour, [min], [sec], [ms])` |
| 135 | +> - `setMinutes(min, [sec], [ms])` |
| 136 | +> - `setSeconds(sec, [ms])` |
| 137 | +> - `setMilliseconds(ms)` |
| 138 | +> - `setTime(timestamp)` (sets the whole date by milliseconds since 01.01.1970 UTC) |
| 139 | +> |
| 140 | +> Parameters in `[]` above are _optional_. |
| 141 | +> If not mentioned, the components are not modified. |
| 142 | +> Every one of them except `setTime()` has a UTC-variant, for instance: `setUTCHours()`. [^6] |
| 143 | +
|
| 144 | +```javascript |
| 145 | +let today = new Date(); |
| 146 | + |
| 147 | +today.setHours(0); // still today, but only the hour is changed to 0 |
| 148 | + |
| 149 | +today.setHours(0, 0, 0, 0); // still today, now sharply 00:00:00 |
| 150 | +``` |
| 151 | + |
| 152 | +## Calculating Time Difference and `Date.now()` |
| 153 | + |
| 154 | +To measure the time elapsed between two given dates, we can use the `Date.getTime()` method. |
| 155 | + |
| 156 | +```javascript |
| 157 | +const d1 = new Date(2021, 12, 11, 5, 13, 32, 21); |
| 158 | +const d2 = new Date(2021, 12, 23, 4, 12, 55); |
| 159 | + |
| 160 | +let timeElapsed = d2.getTime() - d1.getTime(); // => 1033162979 |
| 161 | +``` |
| 162 | + |
| 163 | +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. |
| 164 | + |
| 165 | +## Comparing Dates |
| 166 | + |
| 167 | +We can use `<` and `>` operators to compare two `Date` objects, the date occuring _later being treated as greater_. |
| 168 | + |
| 169 | +The `==` or `===` do not work with `Date`, and output `false` in any case, even if dates are equal. |
| 170 | +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. |
| 171 | + |
| 172 | +```javascript |
| 173 | +const d1 = new Date(2021, 12, 11); |
| 174 | +const d2 = new Date(1990, 11, 23); |
| 175 | + |
| 176 | +d1 > d2; // true |
| 177 | + |
| 178 | +const d1Copy = new Date(d1); // d1Copy will be same as d1 |
| 179 | + |
| 180 | +d1Copy === d1; // false, even though they are same |
| 181 | +d1Copy.getTime() === d1.getTime(); //true |
| 182 | +``` |
| 183 | + |
| 184 | +[^1]: https://javascript.info/date |
| 185 | +[^2]: https://javascript.info/date#setting-date-components |
| 186 | +[^3]: https://javascript.info/date#date-parse-from-a-string |
| 187 | +[^4]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date#several_ways_to_create_a_date_object |
| 188 | +[^5]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date#several_ways_to_create_a_date_object |
| 189 | +[^6]: https://javascript.info/date#access-date-components |
| 190 | + |
| 191 | +[utc-defn]: https://simple.wikipedia.org/wiki/Coordinated_Universal_Time |
| 192 | +[mdn-diff-assumed-timezone]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#differences_in_assumed_time_zone |
0 commit comments