You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 1-js/4-data-structures/11-date/article.md
+34-43Lines changed: 34 additions & 43 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,4 +1,4 @@
1
-
# TODO: Date and time
1
+
# Date and time
2
2
3
3
JavaScript has a built-in object [Date](mdn:js/Date) for date/time management.
4
4
@@ -23,11 +23,17 @@ To create a new `Date` object use one of the following syntaxes:
23
23
: Create a `Date` obeject with the time equal to number of milliseconds (1/1000 of a second) passed after the Jan 1st of 1970 UTC+0.
24
24
25
25
```js run
26
-
// 24 hours after 01.01.1970 UTC+0
26
+
// 0 means 01.01.1970 UTC+0
27
+
let Jan01_1970 = new Date(0);
28
+
alert( Jan01_1970 );
29
+
30
+
// now add 24 hours, get 02.01.1970 UTC+0
27
31
let Jan02_1970 = new Date(24 * 3600 * 1000);
28
32
alert( Jan02_1970 );
29
33
```
30
34
35
+
The number of milliseconds is called a *timestamp*. It is a lightweight numeric representation of a date. We can always create a date from the timestamp number using `new Date(timestamp)` and get the timestamp from the existing `Date` object using `date.getTime()` (see below).
36
+
31
37
`new Date(datestring)`
32
38
: If there is a single argument -- a string, then it is parsed with the `Date.parse` algorithm (see below).
33
39
@@ -101,7 +107,7 @@ alert( date.getUTCHours() );
101
107
Besides the given methods, there are two special ones, that do not have a UTC-variant:
102
108
103
109
`getTime()`
104
-
: Returns a number of milliseconds passed from the January 1st of 1970 UTC+0. The same kind of used in `new Date(milliseconds)` constructor.
110
+
: Returns the timestamp for the date -- a number of milliseconds passed from the January 1st of 1970 UTC+0.
105
111
106
112
`getTimezoneOffset()`
107
113
: Returns the difference between the local time zene and UTC, in minutes:
@@ -363,66 +369,51 @@ The great pack of articles about V8 can be found at <http://mrale.ph>.
363
369
364
370
## Date.parse from a string
365
371
366
-
Все современные браузеры, включая IE9+, понимают даты в упрощённом формате ISO 8601 Extended.
367
-
368
-
Этот формат выглядит так: `YYYY-MM-DDTHH:mm:ss.sssZ`, где:
372
+
The method [Date.parse](mdn:js/Date/parse) can read the date from a string.
369
373
370
-
- `YYYY-MM-DD` -- дата в формате год-месяц-день.
371
-
- Обычный символ `T` используется как разделитель.
- Часть `'Z'` обозначает временную зону -- в формате `+-hh:mm`, либо символ `Z`, обозначающий UTC. По стандарту её можно не указывать, тогда UTC, но в Safari с этим ошибка, так что лучше указывать всегда.
374
+
The format is: `YYYY-MM-DDTHH:mm:ss.sssZ`, where:
374
375
375
-
Также возможны укороченные варианты, например `YYYY-MM-DD` или `YYYY-MM` или даже только `YYYY`.
376
+
- `YYYY-MM-DD` -- is the date: year-month-day.
377
+
- The ordinary character `T` is used as the delimiter.
378
+
- `HH:mm:ss.sss` -- is the time: hours, minutes, seconds and milliseconds.
379
+
- The optional `'Z'` part denotes the time zone in the format `+-hh:mm` or a single `Z` that would mean UTC+0.
376
380
377
-
Метод `Date.parse(str)` разбирает строку `str` в таком формате и возвращает соответствующее ей количество миллисекунд. Если это невозможно, `Date.parse` возвращает `NaN`.
381
+
Shorter variants are also possible, like `YYYY-MM-DD` or `YYYY-MM` or even `YYYY`.
378
382
379
-
Например:
383
+
The call to `Date.parse(str)` parses the string in the given format and returns the timestamp (number of milliseconds from 1 Jan 1970 UTC+0). If the format is invalid, returns `NaN`.
380
384
381
-
```js run
382
-
let msUTC = Date.parse('2012-01-26T13:51:50.417Z'); // зона UTC
let ms = Date.parse('2012-01-26T13:51:50.417-07:00');
391
389
392
-
alert( ms ); // 1327611110417 (число миллисекунд)
390
+
alert( ms ); // 1327611110417 (timestam)
393
391
```
394
392
395
-
````smart header="Формат дат для IE8-"
396
-
До появления спецификации ECMAScript 5 формат не был стандартизован, и браузеры, включая IE8-, имели свои собственные форматы дат. Частично, эти форматы пересекаются.
397
-
398
-
Например, код ниже работает везде, включая старые IE:
393
+
We can instantly create a `new Date` object from the timestamp:
399
394
400
395
```js run
401
-
let ms = Date.parse("January 26, 2011 13:51:50");
396
+
let date = new Date( Date.parse('2012-01-26T13:51:50.417-07:00') );
402
397
403
-
alert( ms );
398
+
alert( date );
404
399
```
405
400
406
-
Вы также можете почитать о старых форматах IE в документации к методу <a href="http://msdn.microsoft.com/en-us/library/k4w173wk%28v=vs.85%29.aspx">MSDN Date.parse</a>.
407
-
408
-
Конечно же, сейчас лучше использовать современный формат. Если же нужна поддержка IE8-, то метод `Date.parse`, как и ряд других современных методов, добавляется библиотекой [es5-shim](https://github.com/kriskowal/es5-shim).
409
-
````
401
+
## Date.now()
410
402
411
-
## Метод Date.now()
403
+
The call to `Date.now()` returns the current timestamp, or, in other words, the number of milliseconds that passed since 01 Jan 1970 till now.
412
404
413
-
Метод `Date.now()` возвращает дату сразу в виде миллисекунд.
405
+
It is semantically equivalent to `new Date().getTime()`, but it does not create an intermediate `Date` object.
414
406
415
-
Технически, он аналогичен вызову `+new Date()`, но в отличие от него не создаёт промежуточный объект даты, а поэтому -- во много раз быстрее.
407
+
It is used mostly for convenience or when the performance is critical, like games in JavaScript or other specialized applications.
416
408
417
-
Его использование особенно рекомендуется там, где производительность при работе с датами критична. Обычно это не на веб-страницах, а, к примеру, в разработке игр на JavaScript.
409
+
## Summary
418
410
419
-
## Итого
411
+
- Date and time in JavaScript are represented with the [Date](mdn:js/Date) object. We can't create "only date" or "only time".
412
+
- Months are counted from the zero (yes, January is a zero month).
413
+
- Days ofweek (for`getDay()`) are also counted from the zero (Sunday).
414
+
-`Date` auto-corrects itself when out-of-range components are set. Goodfor adding/substracting days/months/hours.
415
+
- Dates can be substructed, giving their difference inmilliseconds. That's because a `Date` becomes the timestamp if converted to a number.
416
+
- Use `Date.now()` to get the current timestamp fast.
420
417
421
-
- Дата и время представлены в JavaScript одним объектом: [Date](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/). Создать "только время" при этом нельзя, оно должно быть с датой. Список методов `Date` вы можете найти в справочнике [Date](http://javascript.ru/Date) или выше.
422
-
- Отсчёт месяцев начинается с нуля.
423
-
- Отсчёт дней недели (для `getDay()`) тоже начинается с нуля (и это воскресенье).
424
-
- Объект `Date` удобен тем, что автокорректируется. Благодаря этому легко сдвигать даты.
425
-
- При преобразовании к числу объект `Date` даёт количество миллисекунд, прошедших с 1 января 1970 UTC. Побочное следствие -- даты можно вычитать, результатом будет разница в миллисекундах.
426
-
- Для получения текущей даты в миллисекундах лучше использовать `Date.now()`, чтобы не создавать лишний объект `Date` (кроме IE8-)
427
-
- Для бенчмаркинга лучше использовать `performance.now()` (кроме IE9-), он в 1000 раз точнее.
418
+
Note that unlike many other systems, timestamps in JavaScript are in milliseconds, not in seconds.
0 commit comments