Как вывести текущее время в javascript
Перейти к содержимому

Как вывести текущее время в javascript

  • автор:

Как вывести текущее время в javascript

JavaScript Date objects represent a single moment in time in a platform-independent format. Date objects encapsulate an integral number that represents milliseconds since the midnight at the beginning of January 1, 1970, UTC (the epoch).

Note: TC39 is working on Temporal, a new Date/Time API. Read more about it on the Igalia blog. It is not yet ready for production use!

Description

The epoch, timestamps, and invalid date

A JavaScript date is fundamentally specified as the time in milliseconds that has elapsed since the epoch, which is defined as the midnight at the beginning of January 1, 1970, UTC (equivalent to the UNIX epoch). This timestamp is timezone-agnostic and uniquely defines an instant in history.

Note: While the time value at the heart of a Date object is UTC, the basic methods to fetch the date and time or its components all work in the local (i.e. host system) time zone and offset.

The maximum timestamp representable by a Date object is slightly smaller than the maximum safe integer ( Number.MAX_SAFE_INTEGER , which is 9,007,199,254,740,991). A Date object can represent a maximum of ±8,640,000,000,000,000 milliseconds, or ±100,000,000 (one hundred million) days, relative to the epoch. This the range from April 20, 271821 BC to September 13, 275760 AD. Any attempt to represent a time outside this range results in the Date object holding a timestamp value of NaN , which is an «Invalid Date».

There are various methods that allow you to interact with the timestamp stored in the date:

  • You can interact with the timestamp value directly using the getTime() and setTime() methods.
  • The valueOf() and [@@toPrimitive]() (when passed «number» ) methods — which are automatically called in number coercion — return the timestamp, causing Date objects to behave like their timestamps when used in number contexts.
  • All static methods ( Date.now() , Date.parse() , and Date.UTC() ) return timestamps instead of Date objects.
  • The Date() constructor can be called with a timestamp as the only argument.

Date components and time zones

A date is represented internally as a single number, the timestamp. When interacting with it, the timestamp needs to be interpreted as a structured date-and-time representation. There are always two ways to interpret a timestamp: as a local time or as a Coordinated Universal Time (UTC), the global standard time defined by the World Time Standard. The local timezone is not stored in the date object, but is determined by the host environment (user’s device).

Note: UTC should not be confused with the Greenwich Mean Time (GMT), because they are not always equal — this is explained in more detail in the linked Wikipedia page.

For example, the timestamp 0 represents a unique instant in history, but it can be interpreted in two ways:

  • As a UTC time, it is midnight at the beginning of January 1, 1970, UTC,
  • As a local time in New York (UTC-5), it is 19:00:00 on December 31, 1969.

The getTimezoneOffset() method returns the difference between UTC and the local time in minutes. Note that the timezone offset does not only depend on the current timezone, but also on the time represented by the Date object, because of daylight saving time and historical changes. In essence, the timezone offset is the offset from UTC time, at the time represented by the Date object and at the location of the host environment.

There are two groups of Date methods: one group gets and sets various date components by interpreting the timestamp as a local time, while the other uses UTC.

Component Local UTC
Get Set Get Set
Year getFullYear() setFullYear() getUTCFullYear() setUTCFullYear()
Month getMonth() setMonth() getUTCMonth() setUTCMonth()
Date (of month) getDate() setDate() getUTCDate() setUTCDate()
Hours getHours() setHours() getUTCHours() setUTCHours()
Minutes getMinutes() setMinutes() getUTCMinutes() setUTCMinutes()
Seconds getSeconds() setSeconds() getUTCSeconds() setUTCSeconds()
Milliseconds getMilliseconds() setMilliseconds() getUTCMilliseconds() setUTCMilliseconds()
Day (of week) getDay() N/A getUTCDay() N/A

The Date() constructor can be called with two or more arguments, in which case they are interpreted as the year, month, day, hour, minute, second, and millisecond, respectively, in local time. Date.UTC() works similarly, but it interprets the components as UTC time and also accepts a single argument representing the year.

Note: Some methods, including the Date() constructor, Date.UTC() , and the deprecated getYear() / setYear() methods, interpret a two-digit year as a year in the 1900s. For example, new Date(99, 5, 24) is interpreted as June 24, 1999, not June 24, 99. See Interpretation of two-digit years for more information.

When a segment overflows or underflows its expected range, it usually «carries over to» or «borrows from» the higher segment. For example, if the month is set to 12 (months are zero-based, so December is 11), it become the January of the next year. If the day of month is set to 0, it becomes the last day of the previous month. This also applies to dates specified with the date time string format.

Date time string format

There are many ways to format a date as a string. The JavaScript specification only specifies one format to be universally supported: the date time string format, a simplification of the ISO 8601 calendar date extended format. The format is as follows:

  • YYYY is the year, with four digits ( 0000 to 9999 ), or as an expanded year of + or — followed by six digits. The sign is required for expanded years. -000000 is explicitly disallowed as a valid year.
  • MM is the month, with two digits ( 01 to 12 ). Defaults to 01 .
  • DD is the day of the month, with two digits ( 01 to 31 ). Defaults to 01 .
  • T is a literal character, which indicates the beginning of the time part of the string. The T is required when specifying the time part.
  • HH is the hour, with two digits ( 00 to 23 ). As a special case, 24:00:00 is allowed, and is interpreted as midnight at the beginning of the next day. Defaults to 00 .
  • mm is the minute, with two digits ( 00 to 59 ). Defaults to 00 .
  • ss is the second, with two digits ( 00 to 59 ). Defaults to 00 .
  • sss is the millisecond, with three digits ( 000 to 999 ). Defaults to 000 .
  • Z is the timezone offset, which can either be the literal character Z (indicating UTC), or + or — followed by HH:mm , the offset in hours and minutes from UTC.

Various components can be omitted, so the following are all valid:

  • Date-only form: YYYY , YYYY-MM , YYYY-MM-DD
  • Date-time form: one of the above date-only forms, followed by T , followed by HH:mm , HH:mm:ss , or HH:mm:ss.sss . Each combination can be followed by a time zone offset.

For example, «2011-10-10» (date-only form), «2011-10-10T14:48:00» (date-time form), or «2011-10-10T14:48:00.000+09:00» (date-time form with milliseconds and time zone) are all valid date time strings.

When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as local time. This is due to a historical spec error that was not consistent with ISO 8601 but could not be changed due to web compatibility. See Broken Parser – A Web Reality Issue.

Date.parse() and the Date() constructor both accept strings in the date time string format as input. Furthermore, implementations are allowed to support other date formats when the input fails to match this format.

The toISOString() method returns a string representation of the date in the date time string format, with the time zone offset always set to Z (UTC).

Note: You are encouraged to make sure your input conforms to the date time string format above for maximum compatibility, because support for other formats is not guaranteed. However, there are some formats that are supported in all major implementations — like RFC 2822 format — in which case their usage can be acceptable. Always conduct cross-browser tests to ensure your code works in all target browsers. A library can help if many different formats are to be accommodated.

Non-standard strings can be parsed in any way as desired by the implementation, including the time zone — most implementations use the local time zone by default. Implementations are not required to return invalid date for out-of-bounds date components, although they usually do. A string may have in-bounds date components (with the bounds defined above), but does not represent a date in reality (for example, «February 30»). Implementations behave inconsistently in this case. The Date.parse() page offers more examples about these non-standard cases.

Other ways to format a date

    returns a string in the format 1970-01-01T00:00:00.000Z (the date time string format introduced above, which is simplified ISO 8601). toJSON() calls toISOString() and returns the result. returns a string in the format Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time) , while toDateString() and toTimeString() return the date and time parts of the string, respectively. [@@toPrimitive]() (when passed «string» or «default» ) calls toString() and returns the result. returns a string in the format Thu, 01 Jan 1970 00:00:00 GMT (generalized RFC 7231). , toLocaleTimeString() , and toLocaleString() use locale-specific date and time formats, usually provided by the Intl API.

Constructor

When called as a constructor, returns a new Date object. When called as a function, returns a string representation of the current date and time.

Static methods

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.

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.

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.

Instance properties

These properties are defined on Date.prototype and shared by all Date instances.

The constructor function that created the instance object. For Date instances, the initial value is the Date constructor.

Instance methods

Returns the day of the month ( 1 – 31 ) for the specified date according to local time.

Returns the day of the week ( 0 – 6 ) for the specified date according to local time.

Returns the year (4 digits for 4-digit years) of the specified date according to local time.

Returns the hour ( 0 – 23 ) in the specified date according to local time.

Returns the milliseconds ( 0 – 999 ) in the specified date according to local time.

Returns the minutes ( 0 – 59 ) in the specified date according to local time.

Returns the month ( 0 – 11 ) in the specified date according to local time.

Returns the seconds ( 0 – 59 ) in the specified date according to local time.

Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC. (Negative values are returned for prior times.)

Returns the time-zone offset in minutes for the current locale.

Returns the day (date) of the month ( 1 – 31 ) in the specified date according to universal time.

Returns the day of the week ( 0 – 6 ) in the specified date according to universal time.

Returns the year (4 digits for 4-digit years) in the specified date according to universal time.

Returns the hours ( 0 – 23 ) in the specified date according to universal time.

Returns the milliseconds ( 0 – 999 ) in the specified date according to universal time.

Returns the minutes ( 0 – 59 ) in the specified date according to universal time.

Returns the month ( 0 – 11 ) in the specified date according to universal time.

Returns the seconds ( 0 – 59 ) in the specified date according to universal time.

Returns the year (usually 2–3 digits) in the specified date according to local time. Use getFullYear() instead.

Sets the day of the month for a specified date according to local time.

Sets the full year (e.g. 4 digits for 4-digit years) for a specified date according to local time.

Sets the hours for a specified date according to local time.

Sets the milliseconds for a specified date according to local time.

Sets the minutes for a specified date according to local time.

Sets the month for a specified date according to local time.

Sets the seconds for a specified date according to local time.

Sets the Date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC. Use negative numbers for times prior.

Sets the day of the month for a specified date according to universal time.

Sets the full year (e.g. 4 digits for 4-digit years) for a specified date according to universal time.

Sets the hour for a specified date according to universal time.

Sets the milliseconds for a specified date according to universal time.

Sets the minutes for a specified date according to universal time.

Sets the month for a specified date according to universal time.

Sets the seconds for a specified date according to universal time.

Sets the year (usually 2–3 digits) for a specified date according to local time. Use setFullYear() instead.

Returns the «date» portion of the Date as a human-readable string like ‘Thu Apr 12 2018’ .

Converts a date to a string following the ISO 8601 Extended Format.

Returns a string representing the Date using toISOString() . Intended for use by JSON.stringify() .

Returns a string with a locality sensitive representation of the date portion of this date based on system settings.

Returns a string with a locality-sensitive representation of this date. Overrides the Object.prototype.toLocaleString() method.

Returns a string with a locality-sensitive representation of the time portion of this date, based on system settings.

Returns a string representing the specified Date object. Overrides the Object.prototype.toString() method.

Returns the «time» portion of the Date as a human-readable string.

Converts a date to a string using the UTC timezone.

Returns the primitive value of a Date object. Overrides the Object.prototype.valueOf() method.

Converts this Date object to a primitive value.

Examples

Several ways to create a Date object

The following examples show several ways to create JavaScript dates:

Note: Creating a date from a string has a lot of behavior inconsistencies. See date time string format for caveats on using different formats.

Formats of toString method return values

To get Date, Month and Year or Time

Interpretation of two-digit years

new Date() exhibits legacy undesirable, inconsistent behavior with two-digit year values; specifically, when a new Date() call is given a two-digit year value, that year value does not get treated as a literal year and used as-is but instead gets interpreted as a relative offset — in some cases as an offset from the year 1900 , but in other cases, as an offset from the year 2000 .

So, to create and get dates between the years 0 and 99 , instead use the preferred setFullYear() and getFullYear() methods:.

Calculating elapsed time

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

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.

Дата и время

Встречайте новый встроенный объект: Date. Он содержит дату и время, а также предоставляет методы управления ими.

Например, его можно использовать для хранения времени создания/изменения, для измерения времени или просто для вывода текущей даты.

Создание

Для создания нового объекта Date нужно вызвать конструктор new Date() с одним из следующих аргументов:

Без аргументов – создать объект Date с текущими датой и временем:

Создать объект Date с временем, равным количеству миллисекунд (тысячная доля секунды), прошедших с 1 января 1970 года UTC+0.

Целое число, представляющее собой количество миллисекунд, прошедших с начала 1970 года, называется таймстамп (англ. timestamp).

Это – легковесное численное представление даты. Из таймстампа всегда можно получить дату с помощью new Date(timestamp) и преобразовать существующий объект Date в таймстамп, используя метод date.getTime() (см. ниже).

Датам до 1 января 1970 будут соответствовать отрицательные таймстампы, например:

Если аргумент всего один, и это строка, то из неё «прочитывается» дата. Алгоритм разбора – такой же, как в Date.parse , который мы рассмотрим позже.

Создать объект Date с заданными компонентами в местном часовом поясе. Обязательны только первые два аргумента.

  • year должен состоять из четырёх цифр. Для совместимости также принимаются 2 цифры и рассматриваются как 19xx , к примеру, 98 здесь это тоже самое, что и 1998 , но настоятельно рекомендуется всегда использовать 4 цифры.
  • month начинается с 0 (январь) по 11 (декабрь).
  • Параметр date здесь представляет собой день месяца. Если параметр не задан, то принимается значение 1 .
  • Если параметры hours/minutes/seconds/ms отсутствуют, их значением становится 0 .

Максимальная точность – 1 мс (до 1/1000 секунды):

Получение компонентов даты

Существуют методы получения года, месяца и т.д. из объекта Date :

getFullYear() Получить год (4 цифры) getMonth() Получить месяц, от 0 до 11. getDate() Получить день месяца, от 1 до 31, что несколько противоречит названию метода. getHours(), getMinutes(), getSeconds(), getMilliseconds() Получить, соответственно, часы, минуты, секунды или миллисекунды.

Многие интерпретаторы JavaScript реализуют нестандартный и устаревший метод getYear() , который порой возвращает год в виде двух цифр. Пожалуйста, обходите его стороной. Если нужно значение года, используйте getFullYear() .

Кроме того, можно получить определённый день недели:

getDay() Вернуть день недели от 0 (воскресенье) до 6 (суббота). Несмотря на то, что в ряде стран за первый день недели принят понедельник, в JavaScript начало недели приходится на воскресенье.

Все вышеперечисленные методы возвращают значения в соответствии с местным часовым поясом.

Однако существуют и их UTC-варианты, возвращающие день, месяц, год для временной зоны UTC+0: getUTCFullYear(), getUTCMonth(), getUTCDay(). Для их использования требуется после "get" подставить "UTC" .

Если ваш местный часовой пояс смещён относительно UTC, то следующий код покажет разные часы:

Помимо вышеприведённых методов, существуют два особых метода без UTC-варианта:

Для заданной даты возвращает таймстамп – количество миллисекунд, прошедших с 1 января 1970 года UTC+0.

Возвращает разницу в минутах между UTC и местным часовым поясом:

Установка компонентов даты

Следующие методы позволяют установить компоненты даты и времени:

У всех этих методов, кроме setTime() , есть UTC-вариант, например: setUTCHours() .

Как мы видим, некоторые методы могут устанавливать сразу несколько компонентов даты, например: setHours . Если какая-то компонента не указана, она не меняется.

Автоисправление даты

Автоисправление – это очень полезная особенность объектов Date . Можно устанавливать компоненты даты вне обычного диапазона значений, а объект сам себя исправит.

Неправильные компоненты даты автоматически распределяются по остальным.

Предположим, нам требуется увеличить дату «28 февраля 2016» на два дня. В зависимости от того, високосный это год или нет, результатом будет «2 марта» или «1 марта». Нам об этом думать не нужно. Просто прибавляем два дня. Объект Date позаботится об остальном:

Эту возможность часто используют, чтобы получить дату по прошествии заданного отрезка времени. Например, получим дату «спустя 70 секунд с текущего момента»:

Также можно установить нулевые или даже отрицательные значения. Например:

Преобразование к числу, разность дат

Если объект Date преобразовать в число, то получим таймстамп по аналогии с date.getTime() :

Важный побочный эффект: даты можно вычитать, в результате получаем разность в миллисекундах.

Этот приём можно использовать для измерения времени:

Date.now()

Если нужно просто измерить время, объект Date нам не нужен.

Существует особый метод Date.now() , возвращающий текущую метку времени.

Семантически он эквивалентен new Date().getTime() , однако метод не создаёт промежуточный объект Date . Так что этот способ работает быстрее и не нагружает сборщик мусора.

Данный метод используется из соображений удобства или когда важно быстродействие, например, при разработке игр на JavaScript или других специализированных приложений.

Вероятно, предыдущий пример лучше переписать так:

Бенчмаркинг

Будьте внимательны, если хотите точно протестировать производительность функции, которая зависит от процессора.

Например, сравним две функции, вычисляющие разницу между двумя датами: какая сработает быстрее?

Подобные вычисления, замеряющие производительность, также называют «бенчмарками» (benchmark).

Обе функции делают буквально одно и то же, только одна использует явный метод date.getTime() для получения даты в миллисекундах, а другая полагается на преобразование даты в число. Результат их работы всегда один и тот же.

Но какая функция быстрее?

Для начала можно запустить их много раз подряд и засечь разницу. В нашем случае функции очень простые, так что потребуется хотя бы 100000 повторений.

Вот это да! Метод getTime() работает ощутимо быстрее! Всё потому, что не производится преобразование типов, и интерпретаторам такое намного легче оптимизировать.

Замечательно, это уже что-то. Но до хорошего бенчмарка нам ещё далеко.

Представьте, что при выполнении bench(diffSubtract) процессор параллельно делал что-то ещё, также потребляющее ресурсы. А к началу выполнения bench(diffGetTime) он это уже завершил.

Достаточно реалистичный сценарий в современных многопроцессорных операционных системах.

В итоге у первого бенчмарка окажется меньше ресурсов процессора, чем у второго. Это может исказить результаты.

Для получения наиболее достоверных результатов тестирования производительности весь набор бенчмарков нужно запускать по нескольку раз.

Современные интерпретаторы JavaScript начинают применять продвинутые оптимизации только к «горячему коду», выполняющемуся несколько раз (незачем оптимизировать то, что редко выполняется). Так что в примере выше первые запуски не оптимизированы должным образом. Нелишним будет добавить предварительный запуск для «разогрева»:

Современные интерпретаторы JavaScript выполняют множество оптимизаций. Они могут повлиять на результаты «искусственных тестов» по сравнению с «нормальным использованием», особенно если мы тестируем что-то очень маленькое, например, работу оператора или встроенной функции. Поэтому если хотите серьёзно понять производительность, пожалуйста, изучите, как работают интерпретаторы JavaScript. И тогда вам, вероятно, уже не понадобятся микробенчмарки.

Отличный набор статей о V8 можно найти на https://mrale.ph.

Разбор строки с датой

Метод Date.parse(str) считывает дату из строки.

Формат строки должен быть следующим: YYYY-MM-DDTHH:mm:ss.sssZ , где:

  • YYYY-MM-DD – это дата: год-месяц-день.
  • Символ "T" используется в качестве разделителя.
  • HH:mm:ss.sss – время: часы, минуты, секунды и миллисекунды.
  • Необязательная часть ‘Z’ обозначает часовой пояс в формате +-hh:mm . Если указать просто букву Z , то получим UTC+0.

Возможны и более короткие варианты, например, YYYY-MM-DD или YYYY-MM , или даже YYYY .

Объект Date: Текущая Дата и Время в Javascript

В этом посте хочу затронуть тему работы с датами в Javascript, которая, при первом приближении, может показаться сложной.

Для работы с датами Javascript предоставляет разработчикам встроенный функционал в виде объекта Date .

Экземпляр объекта Date — это момент времени. Методы объекта позволяют управлять не только датами, но и временем.

Рассмотрим 4 способа создать новый объект Date.

1. Использовать конструктор new Date() без передачи дополнительных параметров

Для создания нового объекта Date требуется вызвать конструктор:

Это позволит нам получить новый экземпляр объекта Date , содержащий текущий момент времени.

В качестве нулевой (базовой) даты, Javascript использует 1 Января 1970 00:00:00 UTC . Текущий момент времени — количество миллисекунд, прошедших с нулевой даты.

2. Использовать конструктор new Date() с передачей временной метки, выраженной в миллисекундах

Вероятно, вы сталкивались с временной меткой Unix, которая использует ту же нулевую дату, но представлена не в миллисекундах, а секундах.

Мы можем передать временную метку Unix в объект Date и получить соответствующий момент времени следующим образом:

Если мы передадим 0 в объект Date , то получим нулевую дату 1 Января 1970.

Можно также использовать встроенный метод Date.now() , чтобы получить текущую временную метку в миллисекундах и передать ее в объект Date .

3. Передать дату в объект Date — в формате строки

Мы также можем использовать строчные выражения для передачи в объект Date и получения соответствующего момента времени. В этом случае в объекте Date будет автоматически использоваться метод parse для определения даты и времени, которые мы в него передаем.

Также есть возможность использовать метод Date.parse() , который возвращает временную метку в миллисекундах.

4. Передать набор параметров в объект Date

Еще один способ создать новый экземпляр объекта Date – передать в него набор значений, соответствующих году, месяцу (первый месяц равен 0), дню, часу, минутам, секундам и миллисекундам.

Во всех случаях, указанных выше, мы получаем дату, привязанную к временной зоне нашего компьютера. То есть, используя одинаковые входные данные на разных компьютерах, можно получить разные результаты.

Javascript использует UTC в качестве базовой временной зоны, и производит автоматическую конверсию в локальную временную зону вашего компьютера.

Как Поменять Временную Зону?

У нас есть 2 варианта изменения временной зоны при создании нового экземпляра объекта Date:

  • Использование формата “+Часы”
  • Передать название временной зоны в скобках

Важно учитывать, что, если во 2-м случае вы передадите название временной зоны в неверном формате, Javascript автоматически будет использовать зону UTC. При этом вы не получите сообщения об ошибке.

В первом случае, при передаче часов в неверном формате, Javascript оповестит вас ошибкой “Invalid Date”.

Объект Date: Форматирование

Объект Date содержит ряд методов, которые возвращают дату и время в формате строки:

Javascript: Текущая дата и время (все методы получения)

Для получения значений даты и времени используются следующие методы:

Также есть возможность сразу получать значения даты и времени привязанных не локальной зоне компьютера пользователя, а к зоне UTC.

Установка Компонентов Даты и Времени

Для установки отдельных компонентов даты или времени можно использовать следующие методы:

Другие методы установки отдельных компонентов объекта Date :

Методы setHours() , setMinutes() и setSeconds() помимо базовых значений принимают значения минут, секунд или миллисекунд для более точных установок. Формат ввода выглядит следующим бразом:

Стоить помнить, что если мы укажем обновленное значение часов следующим образом date.setHours(72) , то это приведет к обновлению нашей даты (прибавится 3 дня).

Как Получить Текущее Время из Объекта Javascript Date?

Для получения текущего времени, выраженного в миллисекундах можно использовать метод Date.now() вместо более длинного варианта new Date().getTime() .

Форматирование Даты и Времени в Соответствии с Разными Языками

API Интернационализации (Internationalization API) используется для форматирования даты и времени в соответствии с нужным языком.

В качестве примера, можно привести различия в формате написания дат в России (первым идет день — 31.01.2020) и США (первым идет месяц — 01.31.2020).

Все методы интернационализации дат, времени, а также других единиц (валют) доступны в объекте Intl .

Метод Intl.DateTimeFormat()

В этом посте нас интересует метод Intl.DateTimeFormat() , который используется для форматирования даты и времени.

Рассмотрим следующий пример:

Давайте получим дату в локальном формате:

Теперь получим дату в формате, который используется в США. Для этого используем параметр en-Us (английский язык, используемый в США (US)):

Как Сравнить 2 Даты

Самый простой способ сравнить 2 даты – использовать метод Date.getTime() .

Также для сравнения дат можно использовать условия if :

Использование Библиотеки Moment.js

Рассмотрим несколько примеров ее использования.

Сначала устанавливаем пакет с помощью команды npm install moment .

Список опций форматирования доступен в документации библиотеки (пара примеров):

  • YYYY-MM-DD — 2017-12-14
  • HH:mm:ss — 16:34:10

Один из методов библиотеки, которые часто приходится использовать – fromNow() , который возвращает количество времени, которое прошло с указанной даты.

Я использую этот метод для отображения времени, которое прошло с даты публикации постов в блоге.

Переменные JavaScript var, let и const (в чем отличие и когда использовать)?

Date and time

Let’s meet a new built-in object: Date. It stores the date, time and provides methods for date/time management.

For instance, we can use it to store creation/modification times, to measure time, or just to print out the current date.

Creation

To create a new Date object call new Date() with one of the following arguments:

Without arguments – create a Date object for the current date and time:

Create a Date object with the time equal to number of milliseconds (1/1000 of a second) passed after the Jan 1st of 1970 UTC+0.

An integer number representing the number of milliseconds that has passed since the beginning of 1970 is called a timestamp.

It’s a lightweight numeric representation of a date. We can always create a date from a timestamp using new Date(timestamp) and convert the existing Date object to a timestamp using the date.getTime() method (see below).

Dates before 01.01.1970 have negative timestamps, e.g.:

If there is a single argument, and it’s a string, then it is parsed automatically. The algorithm is the same as Date.parse uses, we’ll cover it later.

Create the date with the given components in the local time zone. Only the first two arguments are obligatory.

  • The year should have 4 digits. For compatibility, 2 digits are also accepted and considered 19xx , e.g. 98 is the same as 1998 here, but always using 4 digits is strongly encouraged.
  • The month count starts with 0 (Jan), up to 11 (Dec).
  • The date parameter is actually the day of month, if absent then 1 is assumed.
  • If hours/minutes/seconds/ms is absent, they are assumed to be equal 0 .

The maximal precision is 1 ms (1/1000 sec):

Access date components

There are methods to access the year, month and so on from the Date object:

getFullYear() Get the year (4 digits) getMonth() Get the month, from 0 to 11. getDate() Get the day of month, from 1 to 31, the name of the method does look a little bit strange. getHours(), getMinutes(), getSeconds(), getMilliseconds() Get the corresponding time components.

Many JavaScript engines implement a non-standard method getYear() . This method is deprecated. It returns 2-digit year sometimes. Please never use it. There is getFullYear() for the year.

Additionally, we can get a day of week:

getDay() Get the day of week, from 0 (Sunday) to 6 (Saturday). The first day is always Sunday, in some countries that’s not so, but can’t be changed.

All the methods above return the components relative to the local time zone.

There are also their UTC-counterparts, that return day, month, year and so on for the time zone UTC+0: getUTCFullYear(), getUTCMonth(), getUTCDay(). Just insert the "UTC" right after "get" .

If your local time zone is shifted relative to UTC, then the code below shows different hours:

Besides the given methods, there are two special ones that do not have a UTC-variant:

Returns the timestamp for the date – a number of milliseconds passed from the January 1st of 1970 UTC+0.

Returns the difference between UTC and the local time zone, in minutes:

Setting date components

The following methods allow to set date/time components:

Every one of them except setTime() has a UTC-variant, for instance: setUTCHours() .

As we can see, some methods can set multiple components at once, for example setHours . The components that are not mentioned are not modified.

Autocorrection

The autocorrection is a very handy feature of Date objects. We can set out-of-range values, and it will auto-adjust itself.

Out-of-range date components are distributed automatically.

Let’s say we need to increase the date “28 Feb 2016” by 2 days. It may be “2 Mar” or “1 Mar” in case of a leap-year. We don’t need to think about it. Just add 2 days. The Date object will do the rest:

That feature is often used to get the date after the given period of time. For instance, let’s get the date for “70 seconds after now”:

We can also set zero or even negative values. For example:

Date to number, date diff

When a Date object is converted to number, it becomes the timestamp same as date.getTime() :

The important side effect: dates can be subtracted, the result is their difference in ms.

That can be used for time measurements:

Date.now()

If we only want to measure time, we don’t need the Date object.

There’s a special method Date.now() that returns the current timestamp.

It is semantically equivalent to new Date().getTime() , but it doesn’t create an intermediate Date object. So it’s faster and doesn’t put pressure on garbage collection.

It is used mostly for convenience or when performance matters, like in games in JavaScript or other specialized applications.

So this is probably better:

Benchmarking

If we want a reliable benchmark of CPU-hungry function, we should be careful.

For instance, let’s measure two functions that calculate the difference between two dates: which one is faster?

Such performance measurements are often called “benchmarks”.

These two do exactly the same thing, but one of them uses an explicit date.getTime() to get the date in ms, and the other one relies on a date-to-number transform. Their result is always the same.

So, which one is faster?

The first idea may be to run them many times in a row and measure the time difference. For our case, functions are very simple, so we have to do it at least 100000 times.

Wow! Using getTime() is so much faster! That’s because there’s no type conversion, it is much easier for engines to optimize.

Okay, we have something. But that’s not a good benchmark yet.

Imagine that at the time of running bench(diffSubtract) CPU was doing something in parallel, and it was taking resources. And by the time of running bench(diffGetTime) that work has finished.

A pretty real scenario for a modern multi-process OS.

As a result, the first benchmark will have less CPU resources than the second. That may lead to wrong results.

For more reliable benchmarking, the whole pack of benchmarks should be rerun multiple times.

For example, like this:

Modern JavaScript engines start applying advanced optimizations only to “hot code” that executes many times (no need to optimize rarely executed things). So, in the example above, first executions are not well-optimized. We may want to add a heat-up run:

Modern JavaScript engines perform many optimizations. They may tweak results of “artificial tests” compared to “normal usage”, especially when we benchmark something very small, such as how an operator works, or a built-in function. So if you seriously want to understand performance, then please study how the JavaScript engine works. And then you probably won’t need microbenchmarks at all.

The great pack of articles about V8 can be found at https://mrale.ph.

Date.parse from a string

The method Date.parse(str) can read a date from a string.

The string format should be: YYYY-MM-DDTHH:mm:ss.sssZ , where:

  • YYYY-MM-DD – is the date: year-month-day.
  • The character "T" is used as the delimiter.
  • HH:mm:ss.sss – is the time: hours, minutes, seconds and milliseconds.
  • The optional ‘Z’ part denotes the time zone in the format +-hh:mm . A single letter Z would mean UTC+0.

Shorter variants are also possible, like YYYY-MM-DD or YYYY-MM or even YYYY .

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *