Как получить дату в javascript
Перейти к содержимому

Как получить дату в javascript

  • автор:

Базовые операции с датами

Создать дату в JavaScript можно с помощью конструктора Date() , который при вызове без параметров ( const date = new Date() ) вернет дату и время вызова в формате YYYY-MM-DDTHH:mm:ss.sssZ где YYYY-MM-DD — год, месяц и день, T — разделитель между датой и временем, HH:mm:ss.sss — часы, минут, секунды и миллисекунды, а Z — настройки временной зоны. Даты в JavaScript представлены в виде количества миллисекунд, прошедших с 1 января 1970 года по UTC поэтому новую дату можно так же создать с помощью метода .now() глобального объекта Date , который вернет количество миллисекунд до вызова.

const date1 = new Date(); //2023-08-29T11:30:31.224Z const date2 = Date.now(); //1693308631228

Поскольку даты содержат точное количество миллисекунд, прошедших с 1 января 1970 года по UTC разницу между ними можно использовать для замера времени между началом и окончанием выполнения какой-либо операции. Для таких целей лучше использовать метод Date.now() вместо конструктора т.к. он гораздо быстрее потому что не создает при вызове промежуточных объектов и возвращает сразу количество миллисекунд, что может быть важно при проведении большого количества замеров подряд.

const start = Date.now(); (function someCalcs() < //какие-то сложные вычисления >)(); console.log(`Время выполнения: $мс`);

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

  • Указать год, месяц, день и т.д. цифрами через запятую
  • Строка вида “ YYYY-MM-DDTHH:mm:ss.sssZ” или ‘December 31, 2023 23:59:59’ фактически такой способ является неявным вызовом метода Date.parse()
  • Другой объект даты
  • Количество миллисекунд, прошедших с 1 января 1970 года по UTC

При указании даты строкой или перечислением цифр не обязательно указывать точное до мс значение. Если не передать количество мс, секунд, минут или часов — они будут автоматически установлены на 0, дни на 1, месяца на 0 (нумерация месяцев начинается с 0). При этом год нужно передавать полностью, а не последние 2 цифры.

Внести изменения в уже существующий объект даты, можно с помощью методов, которые имеют название .set как .setDate() для дней ( .getDay() вернет день недели числом от 0 до 6), .setFullYear() для года ( .setYear() был удален из стандарта т.к. мог принимать не полное значение года) или .setHours() для часов. Если указать при объявлении даты или передать в один из таких методов несуществующее значение, например 20-й месяц или 25-й час — дата автоматически отформатируется и вместо 25 часов добавит к значений дней единицу, а часы установит на 1.

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

const newYear1 = new Date(2023, 11, 31, 23, 59, 59, 999); //2023-12-31T18:59:59.999Z const newYear2 = new Date("2023-12-31T18:59:59.999"); //2023-12-31T13:59:59.999Z const newYear3 = new Date(1704031199999); //передаем количество мс //2023-12-31T13:59:59.999Z console.log(newYear1 === newYear2); //false const ms = newYear1 - newYear2; //при этом разница в ms = 0 //0 newYear1.setDate(32); //устанавливаем несуществующий день в месяце console.log(newYear1); //2024-01-01T18:59:59.999Z дата подстроится под заданные параметры

По аналогии с методами для изменения значений даты, существуют методы для получения части значений. Такие методы имеют название .get или .getUTC для получения получения значений по Гринвичу.

const date = new Date(); //дата и время на момент вызова date.getHours(); //значение часов в месте вызова date.getUTCHours() //значение часов по Гринвичу

Работа с форматированием дат

В JavaScript доступны методы для вывода дат в виде строки разных форматов:

  • .toString()
    • не принимает параметров и возвращает строку в виде: день недели (Mon), первые три буквы месяца (Aug), день (28), год (2023), время без мс (12:45:30), часовой пояс относительно UTC (GMT-0700) и название часового пояса в скобках (Pacific Daylight Time).
    • аналогичен .toString() , но возвращает только дату без времени.
    • аналогичен .toString() , но возвращает только время без даты.
    • аналогичен .toString() , но возвращает дату по Гринвичу.
    • принимает настройки локализации (язык и название страны) и опции (например формат отображения часов в виде 24 или am/pm) и возвращает строку в принятом в указанной стране и языке формате.
    • аналогичен .toLocalString() , но возвращает только дату без времени.
    • аналогичен .toLocalString() , но возвращает только время без даты.
    const date = new Date(); //стандартное форматирование //2023-08-29T14:47:07.820Z console.log(date.toString()); //в строку //Tue Aug 29 2023 19:47:07 GMT+0500 (Yekaterinburg Standard Time) console.log(date.toDateString()); //только дата //Tue Aug 29 2023 console.log(date.toTimeString()); //только время //19:47:07 GMT+0500 (Yekaterinburg Standard Time) console.log(date.toUTCString()); //по Гринвичу //Tue, 29 Aug 2023 14:47:07 GMT console.log(date.toLocaleString("en-US")); //англичйский США //8/29/2023, 7:47:07 PM console.log(date.toLocaleString("en-US", < hour12: false >)); //то же но 24 часовой формат //8/29/2023, 19:47:07 console.log(date.toLocaleDateString("de-DE")); //только дата немецкий Германия //29.8.2023 console.log(date.toLocaleTimeString("ko-KR")); //только время корейский Корея //오후 7:47:07

    Date можно сериализовать в формат JSON с помощью метода .toJSON() . Конструктор конечно же прекрасно распарсит такую строку.

    const toJSON = new Date().toJSON(); //2023-08-29T14:51:52.158Z const toDate = new Date(toJSON); //2023-08-29T14:51:52.158Z console.log(typeof toJSON); //string console.log(typeof toDate);//object

    Заключение

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

    Дата и Время

    Материал на этой странице устарел, поэтому скрыт из оглавления сайта.

    Более новая информация по этой теме находится на странице https://learn.javascript.ru/date.

    Для работы с датой и временем в JavaScript используются объекты Date.

    Создание

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

    Создаёт объект Date с текущей датой и временем:

    var now = new Date(); alert( now );

    new Date(milliseconds)

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

    // 24 часа после 01.01.1970 GMT+0 var Jan02_1970 = new Date(3600 * 24 * 1000); alert( Jan02_1970 );

    new Date(datestring)

    Если единственный аргумент – строка, используется вызов Date.parse (см. далее) для чтения даты из неё.

    new Date(year, month, date, hours, minutes, seconds, ms)

    Дату можно создать, используя компоненты в местной временной зоне. Для этого формата обязательны только первые два аргумента. Отсутствующие параметры, начиная с hours считаются равными нулю, а date – единице.

    • Год year должен быть из 4 цифр.
    • Отсчёт месяцев month начинается с нуля 0. Например:

    new Date(2011, 0, 1, 0, 0, 0, 0); // // 1 января 2011, 00:00:00 new Date(2011, 0, 1); // то же самое, часы/секунды по умолчанию равны 0

    Дата задана с точностью до миллисекунд:

    var date = new Date(2011, 0, 1, 2, 3, 4, 567); alert( date ); // 1.01.2011, 02:03:04.567

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

    Для доступа к компонентам даты-времени объекта Date используются следующие методы:

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

    Не getYear() , а getFullYear()

    Некоторые браузеры реализуют нестандартный метод getYear() . Где-то он возвращает только две цифры из года, где-то четыре. Так или иначе, этот метод отсутствует в стандарте JavaScript. Не используйте его. Для получения года есть getFullYear() .

    Дополнительно можно получить день недели:

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

    Все методы, указанные выше, возвращают результат для местной временной зоны.

    Существуют также UTC-варианты этих методов, возвращающие день, месяц, год и т.п. для зоны GMT+0 (UTC): getUTCFullYear() , getUTCMonth() , getUTCDay() . То есть, сразу после «get» вставляется «UTC» .

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

    // текущая дата var date = new Date(); // час в текущей временной зоне alert( date.getHours() ); // сколько сейчас времени в Лондоне? // час в зоне GMT+0 alert( date.getUTCHours() );

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

    Возвращает число миллисекунд, прошедших с 1 января 1970 года GMT+0, то есть того же вида, который используется в конструкторе new Date(milliseconds) .

    Возвращает разницу между местным и UTC-временем, в минутах.

    alert( new Date().getTimezoneOffset() ); // Для GMT-1 выведет 60

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

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

    • setFullYear(year [, month, date])
    • setMonth(month [, date])
    • setDate(date)
    • setHours(hour [, min, sec, ms])
    • setMinutes(min [, sec, ms])
    • setSeconds(sec [, ms])
    • setMilliseconds(ms)
    • setTime(milliseconds) (устанавливает всю дату по миллисекундам с 01.01.1970 UTC)

    Все они, кроме setTime() , обладают также UTC-вариантом, например: setUTCHours() .

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

    var today = new Date; today.setHours(0); alert( today ); // сегодня, но час изменён на 0 today.setHours(0, 0, 0, 0); alert( today ); // сегодня, ровно 00:00:00.

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

    Автоисправление – очень удобное свойство объектов Date . Оно заключается в том, что можно устанавливать заведомо некорректные компоненты (например 32 января), а объект сам себя поправит.

    var d = new Date(2013, 0, 32); // 32 января 2013 . alert(d); // . это 1 февраля 2013!

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

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

    var d = new Date(2011, 1, 28); d.setDate(d.getDate() + 2); alert( d ); // 2 марта, 2011

    Также это используют для получения даты, отдалённой от имеющейся на нужный промежуток времени. Например, получим дату на 70 секунд большую текущей:

    var d = new Date(); d.setSeconds(d.getSeconds() + 70); alert( d ); // выведет корректную дату

    Можно установить и нулевые, и даже отрицательные компоненты. Например:

    var d = new Date; d.setDate(1); // поставить первое число месяца alert( d ); d.setDate(0); // нулевого числа нет, будет последнее число предыдущего месяца alert( d );
    var d = new Date; d.setDate(-1); // предпоследнее число предыдущего месяца alert( d );

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

    Когда объект Date используется в числовом контексте, он преобразуется в количество миллисекунд:

    alert(+new Date) // +date то же самое, что: +date.valueOf()

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

    Это используют для измерения времени:

    var start = new Date; // засекли время // что-то сделать for (var i = 0; i < 100000; i++) < var doSomething = i * i * i; >var end = new Date; // конец измерения alert( "Цикл занял " + (end - start) + " ms" );

    Бенчмаркинг

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

    Как узнать, какой быстрее?

    Для примера возьмём две функции, которые бегают по массиву:

    function walkIn(arr) < for (var key in arr) arr[key]++ >function walkLength(arr)

    Чтобы померить, какая из них быстрее, нельзя запустить один раз walkIn , один раз walkLength и замерить разницу. Одноразовый запуск ненадёжен, любая мини-помеха исказит результат.

    Для правильного бенчмаркинга функция запускается много раз, чтобы сам тест занял существенное время. Это сведёт влияние помех к минимуму. Сложную функцию можно запускать 100 раз, простую – 1000 раз…

    Померяем, какая из функций быстрее:

    var arr = []; for (var i = 0; i < 1000; i++) arr[i] = 0; function walkIn(arr) < for (var key in arr) arr[key]++; >function walkLength(arr) < for (var i = 0; i < arr.length; i++) arr[i]++; >function bench(f) < var date = new Date(); for (var i = 0; i < 10000; i++) f(arr); return new Date() - date; >alert( 'Время walkIn: ' + bench(walkIn) + 'мс' ); alert( 'Время walkLength: ' + bench(walkLength) + 'мс' );

    Теперь представим себе, что во время первого бенчмаркинга bench(walkIn) компьютер что-то делал параллельно важное (вдруг) и это занимало ресурсы, а во время второго – перестал. Реальная ситуация? Конечно реальна, особенно на современных ОС, где много процессов одновременно.

    Гораздо более надёжные результаты можно получить, если весь пакет тестов прогнать много раз.

    var arr = []; for (var i = 0; i < 1000; i++) arr[i] = 0; function walkIn(arr) < for (var key in arr) arr[key]++; >function walkLength(arr) < for (var i = 0; i < arr.length; i++) arr[i]++; >function bench(f) < var date = new Date(); for (var i = 0; i < 1000; i++) f(arr); return new Date() - date; >// bench для каждого теста запустим много раз, чередуя var timeIn = 0, timeLength = 0; for (var i = 0; i < 100; i++) < timeIn += bench(walkIn); timeLength += bench(walkLength); >alert( 'Время walkIn: ' + timeIn + 'мс' ); alert( 'Время walkLength: ' + timeLength + 'мс' );

    Более точное время с performance.now()

    В современных браузерах (кроме IE9-) вызов performance.now() возвращает количество миллисекунд, прошедшее с начала загрузки страницы. Причём именно с самого начала, до того, как загрузился HTML-файл, если точнее – с момента выгрузки предыдущей страницы из памяти.

    Так что это время включает в себя всё, включая начальное обращение к серверу.

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

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

    console.time(метка) и console.timeEnd(метка)

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

    • console.time(метка) – включить внутренний хронометр браузера с меткой.
    • console.timeEnd(метка) – выключить внутренний хронометр браузера с меткой и вывести результат.

    Параметр «метка» используется для идентификации таймера, чтобы можно было делать много замеров одновременно и даже вкладывать измерения друг в друга.

    В коде ниже таймеры walkIn , walkLength – конкретные тесты, а таймер «All Benchmarks» – время «на всё про всё»:

    var arr = []; for (var i = 0; i < 1000; i++) arr[i] = 0; function walkIn(arr) < for (var key in arr) arr[key]++; >function walkLength(arr) < for (var i = 0; i < arr.length; i++) arr[i]++; >function bench(f) < for (var i = 0; i < 10000; i++) f(arr); >console.time("All Benchmarks"); console.time("walkIn"); bench(walkIn); console.timeEnd("walkIn"); console.time("walkLength"); bench(walkLength); console.timeEnd("walkLength"); console.timeEnd("All Benchmarks");

    При запуске этого примера нужно открыть консоль, иначе вы ничего не увидите.

    Внимание, оптимизатор!

    Современные интерпретаторы JavaScript делают массу оптимизаций, например:

    1. Автоматически выносят инвариант, то есть постоянное в цикле значение типа arr.length , за пределы цикла.
    2. Стараются понять, значения какого типа хранит данная переменная или массив, какую структуру имеет объект и, исходя из этого, оптимизировать внутренние алгоритмы.
    3. Выполняют простейшие операции, например сложение явно заданных чисел и строк, на этапе компиляции.
    4. Могут обнаружить, что некий код, например присваивание к неиспользуемой локальной переменной, ни на что не влияет и вообще исключить его из выполнения, хотя делают это редко.

    Эти оптимизации могут влиять на результаты тестов, поэтому измерять скорость базовых операций JavaScript («проводить микробенчмаркинг») до того, как вы изучите внутренности JavaScript-интерпретаторов и поймёте, что они реально делают на таком коде, не рекомендуется.

    Форматирование и вывод дат

    Во всех браузерах, кроме IE10-, поддерживается новый стандарт Ecma 402, который добавляет специальные методы для форматирования дат.

    Это делается вызовом date.toLocaleString(локаль, опции) , в котором можно задать много настроек. Он позволяет указать, какие параметры даты нужно вывести, и ряд настроек вывода, после чего интерпретатор сам сформирует строку.

    Пример с почти всеми параметрами даты и русским, затем английским (США) форматированием:

    var date = new Date(2014, 11, 31, 12, 30, 0); var options = < era: 'long', year: 'numeric', month: 'long', day: 'numeric', weekday: 'long', timezone: 'UTC', hour: 'numeric', minute: 'numeric', second: 'numeric' >; alert( date.toLocaleString("ru", options) ); // среда, 31 декабря 2014 г. н.э. 12:30:00 alert( date.toLocaleString("en-US", options) ); // Wednesday, December 31, 2014 Anno Domini 12:30:00 PM

    Вы сможете подробно узнать о них в статье Intl: интернационализация в JavaScript, которая посвящена этому стандарту.

    Методы вывода без локализации:

    toString() , toDateString() , toTimeString() Возвращают стандартное строчное представление, не заданное жёстко в стандарте, а зависящее от браузера. Единственное требование к нему – читаемость человеком. Метод toString возвращает дату целиком, toDateString() и toTimeString() – только дату и время соответственно.

    var d = new Date(); alert( d.toString() ); // вывод, похожий на 'Wed Jan 26 2011 16:40:50 GMT+0300'

    toUTCString() То же самое, что toString() , но дата в зоне UTC.

    toISOString() Возвращает дату в формате ISO Детали формата будут далее. Поддерживается современными браузерами, не поддерживается IE8-.

    var d = new Date(); alert( d.toISOString() ); // вывод, похожий на '2011-01-26T13:51:50.417Z'

    Если хочется иметь большую гибкость и кросс-браузерность, то также можно воспользоваться специальной библиотекой, например Moment.JS или написать свою функцию форматирования.

    Разбор строки, Date.parse

    Все современные браузеры, включая IE9+, понимают даты в упрощённом формате ISO 8601 Extended.

    Этот формат выглядит так: YYYY-MM-DDTHH:mm:ss.sssZ , где:

    • YYYY-MM-DD – дата в формате год-месяц-день.
    • Обычный символ T используется как разделитель.
    • HH:mm:ss.sss – время: часы-минуты-секунды-миллисекунды.
    • Часть ‘Z’ обозначает временную зону – в формате +-hh:mm , либо символ Z , обозначающий UTC. По стандарту её можно не указывать, тогда UTC, но в Safari с этим ошибка, так что лучше указывать всегда.

    Также возможны укороченные варианты, например YYYY-MM-DD или YYYY-MM или даже только YYYY .

    Метод Date.parse(str) разбирает строку str в таком формате и возвращает соответствующее ей количество миллисекунд. Если это невозможно, Date.parse возвращает NaN .

    var msUTC = Date.parse('2012-01-26T13:51:50.417Z'); // зона UTC alert( msUTC ); // 1327571510417 (число миллисекунд)

    С таймзоной -07:00 GMT :

    var ms = Date.parse('2012-01-26T13:51:50.417-07:00'); alert( ms ); // 1327611110417 (число миллисекунд)

    Формат дат для IE8-

    До появления спецификации ECMAScript 5 формат не был стандартизован, и браузеры, включая IE8-, имели свои собственные форматы дат. Частично, эти форматы пересекаются.

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

    var ms = Date.parse("January 26, 2011 13:51:50"); alert( ms );

    Вы также можете почитать о старых форматах IE в документации к методу MSDN Date.parse.

    Конечно же, сейчас лучше использовать современный формат. Если же нужна поддержка IE8-, то метод Date.parse , как и ряд других современных методов, добавляется библиотекой es5-shim.

    Метод Date.now()

    Метод Date.now() возвращает дату сразу в виде миллисекунд.

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

    Его использование особенно рекомендуется там, где производительность при работе с датами критична. Обычно это не на веб-страницах, а, к примеру, в разработке игр на JavaScript.

    Итого

    • Дата и время представлены в JavaScript одним объектом: Date. Создать «только время» при этом нельзя, оно должно быть с датой. Список методов Date вы можете найти в справочнике Date или выше.
    • Отсчёт месяцев начинается с нуля.
    • Отсчёт дней недели (для getDay() ) тоже начинается с нуля (и это воскресенье).
    • Объект Date удобен тем, что автокорректируется. Благодаря этому легко сдвигать даты.
    • При преобразовании к числу объект Date даёт количество миллисекунд, прошедших с 1 января 1970 UTC. Побочное следствие – даты можно вычитать, результатом будет разница в миллисекундах.
    • Для получения текущей даты в миллисекундах лучше использовать Date.now() , чтобы не создавать лишний объект Date (кроме IE8-)
    • Для бенчмаркинга лучше использовать performance.now() (кроме IE9-), он в 1000 раз точнее.

    Задачи

    Вывести дату в формате дд.мм.гг

    важность: 3

    Напишите функцию formatDate(date) , которая выводит дату date в формате дд.мм.гг :

    var d = new Date(2014, 0, 30); // 30 января 2014 alert( formatDate(d) ); // '30.01.14'

    P.S. Обратите внимание, ведущие нули должны присутствовать, то есть 1 января 2001 должно быть 01.01.01, а не 1.1.1.

    Получим компоненты один за другим.

      День можно получить как date.getDate() . При необходимости добавим ведущий ноль:

    var dd = date.getDate(); if (dd < 10) dd = '0' + dd;
    var mm = date.getMonth() + 1; // месяц 1-12 if (mm < 10) mm = '0' + mm;
    var yy = date.getFullYear() % 100; if (yy < 10) yy = '0' + yy;

    Как получить текущую дату js

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

    const now = new Date(); console.log(now); // => 2021-12-30T07:34:00.537Z 

    Теперь можно извлечь из объекта дату:

    const year = now.getFullYear(); const month = now.getMonth(); // нумерация месяцев начинается с 0 const day = now.getDate(); console.log(`$day>.$month + 1>.$year>`); // => 30.12.2021 

    Date

    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 is 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".

    .log(new Date(8.64e15).toString()); // "Sat Sep 13 275760 00:00:00 GMT+0000 (Coordinated Universal Time)" console.log(new Date(8.64e15 + 1).toString()); // "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-MM-DDTHH:mm:ss.sssZ
    • 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

    • toISOString() 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.
    • toString() 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.
    • toUTCString() returns a string in the format Thu, 01 Jan 1970 00:00:00 GMT (generalized RFC 7231).
    • toLocaleDateString() , 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.

    const today = new Date(); const birthday = new Date("December 17, 1995 03:24:00"); // DISCOURAGED: may not work in all runtimes const birthday2 = new Date("1995-12-17T03:24:00"); // This is standardized and will work reliably const birthday3 = new Date(1995, 11, 17); // the month is 0-indexed const birthday4 = new Date(1995, 11, 17, 3, 24, 0); const birthday5 = new Date(628021800000); // passing epoch timestamp 

    Formats of toString method return values

    const date = new Date("2020-05-12T23:50:21.817Z"); date.toString(); // Tue May 12 2020 18:50:21 GMT-0500 (Central Daylight Time) date.toDateString(); // Tue May 12 2020 date.toTimeString(); // 18:50:21 GMT-0500 (Central Daylight Time) date[Symbol.toPrimitive]("string"); // Tue May 12 2020 18:50:21 GMT-0500 (Central Daylight Time) date.toISOString(); // 2020-05-12T23:50:21.817Z date.toJSON(); // 2020-05-12T23:50:21.817Z date.toUTCString(); // Tue, 12 May 2020 23:50:21 GMT date.toLocaleString(); // 5/12/2020, 6:50:21 PM date.toLocaleDateString(); // 5/12/2020 date.toLocaleTimeString(); // 6:50:21 PM 

    To get Date, Month and Year or Time

    const date = new Date("2000-01-17T16:45:30"); const [month, day, year] = [ date.getMonth(), date.getDate(), date.getFullYear(), ]; // [0, 17, 2000] as month are 0-indexed const [hour, minutes, seconds] = [ date.getHours(), date.getMinutes(), date.getSeconds(), ]; // [16, 45, 30] 

    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 .

    let date = new Date(98, 1); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT) date = new Date(22, 1); // Wed Feb 01 1922 00:00:00 GMT+0000 (GMT) date = new Date("2/1/22"); // Tue Feb 01 2022 00:00:00 GMT+0000 (GMT) // Legacy method; always interprets two-digit year values as relative to 1900 date.setYear(98); date.toString(); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT) date.setYear(22); date.toString(); // Wed Feb 01 1922 00:00:00 GMT+0000 (GMT) 

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

    // Preferred method; never interprets any value as being a relative offset, // but instead uses the year value as-is date.setFullYear(98); date.getFullYear(); // 98 (not 1998) date.setFullYear(22); date.getFullYear(); // 22 (not 1922, not 2022) 

    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.

    // Using Date objects const start = Date.now(); // The event to time goes here: doSomethingForALongTime(); const end = Date.now(); const elapsed = end - start; // elapsed time in milliseconds 
    // Using built-in methods const start = new Date(); // The event to time goes here: doSomethingForALongTime(); const end = new Date(); const elapsed = end.getTime() - start.getTime(); // elapsed time in milliseconds 
    // To test a function and get back its return function printElapsedTime(testFn)  const startTime = Date.now(); const result = testFn(); const endTime = Date.now(); console.log(`Elapsed time: $String(endTime - startTime)> milliseconds`); return result; > const yourFunctionReturn = printElapsedTime(yourFunction); 

    Note: In browsers that support the Web Performance API's high-resolution time feature, Performance.now() can provide more reliable and precise measurements of elapsed time than Date.now() .

    Get the number of seconds since the ECMAScript Epoch

    const seconds = Math.floor(Date.now() / 1000); 

    In this case, it's important to return only an integer—so a simple division won't do. It's also important to only return actually elapsed seconds. (That's why this code uses Math.floor() , and not Math.round() .)

    Specifications

    Specification
    ECMAScript Language Specification
    # sec-date-objects

    Browser compatibility

    BCD tables only load in the browser

    See also

    Found a content problem with this page?

    • Edit the page on GitHub.
    • Report the content issue.
    • View the source on GitHub.

    This page was last modified on Sep 25, 2023 by MDN contributors.

    Your blueprint for a better internet.

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

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