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 .
How do I get the current date in JavaScript?
![]()
Use new Date() to generate a new Date object containing the current date and time.
This will give you today’s date in the format of mm/dd/yyyy.
Simply change today = mm +’/’+ dd +’/’+ yyyy; to whatever format you wish.
Use the replace option if you’re going to reuse the utc variable, such as new Date(utc) , as Firefox and Safari don’t recognize a date with dashes.
![]()
The shortest possible.
To get format like «2018-08-03»:
To get format like «8/3/2018»:
Also, you can pass locale as argument, for example toLocaleDateString(«sr») , etc.
If you want something simple pretty to the end-user . Also, fixed a small suffix issue in the first version below. Now properly returns suffix.
UBBER UPDATE After much procrastination, I’ve finally GitHubbed and updated this with the final solution I’ve been using for myself. It’s even had some last-minute edits to make it sweeter! If you’re looking for the old jsFiddle, please see this.
This update comes in 2 flavors, still relatively small, though not as small as my above, original answer. If you want extremely small, go with that.
Also Note: This is still less bloated than moment.js. While moment.js is nice, imo, it has too many secular methods, which require learning moment as if it were a language. Mine here uses the same common format as PHP: date.
Quick Links
-
5.08 KB 4.16 KB
Flavor 1 new Date().format(String) My Personal Fav. I know the taboo but works great on the Date Object. Just be aware of any other mods you may have to the Date Object.
Flavor 2 dateFormat(Date, String) More traditional all-in-one method. Has all the ability of the previous, but is called via the method with Date param.
BONUS Flavor (requires jQuery) $.date(Date, String) This contains much more than just a simple format option. It extends the base Date object and includes methods such as addDays . For more information, please see the Git.
In this mod, the format characters are inspired by PHP: date. For a complete list, please see my README
This mod also has a much longer list of pre-made formats. To use a premade format, simply enter its key name. dateFormat(new Date(), ‘pretty-a’);
- ‘compound’
- ‘commonLogFormat’ == ‘d/M/Y:G:i:s’
- ‘exif’ == ‘Y:m:d G:i:s’
- ‘isoYearWeek’ == ‘Y\\WW’
- ‘isoYearWeek2’ == ‘Y-\\WW’
- ‘isoYearWeekDay’ == ‘Y\\WWj’
- ‘isoYearWeekDay2’ == ‘Y-\\WW-j’
- ‘mySQL’ == ‘Y-m-d h:i:s’
- ‘postgreSQL’ == ‘Y.z’
- ‘postgreSQL2’ == ‘Yz’
- ‘soap’ == ‘Y-m-d\\TH:i:s.u’
- ‘soap2’ == ‘Y-m-d\\TH:i:s.uP’
- ‘unixTimestamp’ == ‘@U’
- ‘xmlrpc’ == ‘Ymd\\TG:i:s’
- ‘xmlrpcCompact’ == ‘Ymd\\tGis’
- ‘wddx’ == ‘Y-n-j\\TG:i:s’
- ‘AMERICAN’ == ‘F j Y’
- ‘AMERICANSHORT’ == ‘m/d/Y’
- ‘AMERICANSHORTWTIME’ == ‘m/d/Y h:i:sA’
- ‘ATOM’ == ‘Y-m-d\\TH:i:sP’
- ‘COOKIE’ == ‘l d-M-Y H:i:s T’
- ‘EUROPEAN’ == ‘j F Y’
- ‘EUROPEANSHORT’ == ‘d.m.Y’
- ‘EUROPEANSHORTWTIME’ == ‘d.m.Y H:i:s’
- ‘ISO8601’ == ‘Y-m-d\\TH:i:sO’
- ‘LEGAL’ == ‘j F Y’
- ‘RFC822’ == ‘D d M y H:i:s O’
- ‘RFC850’ == ‘l d-M-y H:i:s T’
- ‘RFC1036’ == ‘D d M y H:i:s O’
- ‘RFC1123’ == ‘D d M Y H:i:s O’
- ‘RFC2822’ == ‘D d M Y H:i:s O’
- ‘RFC3339’ == ‘Y-m-d\\TH:i:sP’
- ‘RSS’ == ‘D d M Y H:i:s O’
- ‘W3C’ == ‘Y-m-d\\TH:i:sP’
- ‘pretty-a’ == ‘g:i.sA l jS \\o\\f F Y’
- ‘pretty-b’ == ‘g:iA l jS \\o\\f F Y’
- ‘pretty-c’ == ‘n/d/Y g:iA’
- ‘pretty-d’ == ‘n/d/Y’
- ‘pretty-e’ == ‘F jS — g:ia’
- ‘pretty-f’ == ‘g:iA’
As you may notice, you can use double \ to escape a character.


If you just want a date without time info, use:

The result will be like
If you’re looking for a lot more granular control over the date formats, I thoroughly recommend checking out momentjs. Terrific library — and only 5KB. http://momentjs.com/
Also, you can call method toLocaleDateString with two parameters:
More about this method on MDN.



To break it down into steps:
(new Date()).toString() gives «Fri Jun 28 2013 15:30:18 GMT-0700 (PDT)»
(new Date()).toString().split(‘ ‘) divides the above string on each space and returns an array as follows: [«Fri», «Jun», «28», «2013», «15:31:14», «GMT-0700», «(PDT)»]
(new Date()).toString().split(‘ ‘).splice(1,3).join(‘ ‘) takes the second, third and fourth values from the above array, joins them with spaces, and returns a string «Jun 28 2013»

This works every time:

Most of the other answers are providing the date with time.
If you only need date.If you want it in / format use replaceAll .
If you want other formats then best to use momentjs .
Cleaner, simpler version:
Result varies according to the user’s locale:

If you are happy with YYYY-MM-DD format, this will do the job as well.
You can use Date.js library which extens Date object, thus you can have .today() method.
Using the JavaScript built-in Date.prototype.toLocaleDateString() (more options are in the MDN documentation):
We can get similar behavior using Intl.DateTimeFormat which has decent browser support. Similar to toLocaleDateString() , we can pass an object with options:

You can get the current date call the static method now like this:

Varun’s answer does not account for TimezoneOffset. Here is a version that does:
The TimezoneOffset is minutes, while the Date constructor takes milliseconds, thus the multiplication by 60000 .
As toISOString() will only return current UTC time , not local time. We have to make a date by using ‘.toString()’ function to get date in yyyy-MM-dd format like
To get date and time into in yyyy-MM-ddTHH:mm:ss format
To get date and time into in yyyy-MM-dd HH:mm:ss format

The Shortest Answer is: new Date().toJSON().slice(0,10)
If you want a simple DD/MM/YYYY format, I’ve just come up with this simple solution, although it doesn’t prefix missing zeros.
We use here standard JS functionalities: template literals, Date object which is cast to string, and slice. This is probably shortest solution which meet OP requirements (no time, only date)

LATEST EDIT: 8/23/19 The date-fns library works much like moment.js but has a WAY smaller footprint. It lets you cherry pick which functions you want to include in your project so you don’t have to compile the whole library to format today’s date. If a minimal 3rd party lib isn’t an option for your project, I endorse the accepted solution by Samuel Meddows up top.
Preserving history below because it helped a few people. But for the record it’s pretty hacky and liable to break without warning, as are most of the solutions on this post
EDIT 2/7/2017 A one-line JS solution:
var todaysDate = new Date(Date.now()).toLocaleString().slice(0,3).match(/[0-9]/i) ? new Date(Date.now()).toLocaleString().split(‘ ‘)[0].split(‘,’)[0] : new Date(Date.now()).toLocaleString().split(‘ ‘)[1] + » » + new Date(Date.now()).toLocaleString().split(‘ ‘)[2] + » » + new Date(Date.now()).toLocaleString().split(‘ ‘)[3];
edge, ff latest, & chrome return todaysDate = «2/7/2017»
«works»* in IE10+Explanation
I found out that IE10 and IE Edge do things a bit differently.. go figure. with new Date(Date.now()).toLocaleString() as input,
I could write a big long function and FTFY. But you really ought to use moment.js for this stuff. My script merely cleans this up and gives you the expanded traditional US notation: > todaysDate = «March 06, 2017»
IE EDGE returns:
Of course it couldn’t be that easy. Edge’s date string has invisible «•» characters between each visible one. So not only will we now be checking if the first character is a number, but the first 3 characters, since it turns out that any single character in the whole date range will eventually be a dot or a slash at some point. So to keep things simple, just .slice() the first three chars (tiny buffer against future shenanigans) and then check for numbers. It should probably be noted that these invisible dots could potentially persist in your code. I’d maybe dig into that if you’ve got bigger plans than just printing this string to your view.
JavaScript Объекты даты
JavaScript Объект даты позволяет нам работать с датами:
Пример
JavaScript Вывод даты
По умолчанию JavaScript будет использовать часовой пояс браузера и отображать дату в виде полнотекстовой строки:
Вы узнаете гораздо больше о том, как отображать даты, позже в этом учебнике.
Создание объектов даты
Объекты даты создаются с помощью конструктора new Date() .
Есть 4 пути создания нового объекта даты:
new Date()
new Date() создает новый объект даты с текущими датой и временем:
Пример
Объекты даты статичны. Компьютерное время идёт, а объекты даты — нет.
new Date(year, month, . )
new Date(year, month, . ) создает новый объект даты с указанной датой и временем.
7 чисел определяют год, месяц, день, час, минуту, секунду и миллисекунду (в указанном порядке):
Пример
Примечание: JavaScript считает месяцы от 0 до 11:
December = 11.
Указание месяца выше 11 не приведет к ошибке, но добавит переполнение к следующему году:
Указание дня выше максимального не приведет к ошибке, но добавит переполнение к следующему месяцу:
Использование 6, 4, 3 или 2 чисел
6 цифр определяют год, месяц, день, час, минуту, секунду:
Пример
5 цифр указывают год, месяц, день, час и минуту:
Пример
4 числа определяют год, месяц, день и час:
Пример
3 числа указывают год, месяц и день:
Пример
2 числа указывают год и месяц:
Пример
Вы не можете пропустить месяц. Если вы укажете только один параметр, он будет считаться миллисекундами.
Пример
Предыдущий век
Одно- и двузначные годы будут интерпретироваться как 19xx:
Пример
Пример
new Date(dateString)
new Date(dateString) создает новый объект даты из строки даты:
Пример
Строки даты описаны в следующей главе.
JavaScript сохраняет даты в миллисекундах
JavaScript хранит даты в миллисекундах с 1 января 1970 года, 00:00:00 UTC (всемирное координированное время).
Нулевое время — 01 января, 1970 00:00:00 UTC.
Текущее время: миллисекунд после 1 января 1970 г.
new Date(milliseconds)
new Date(milliseconds) создает новый объект даты как нулевое время плюс миллисекунды:
Пример
01 января 1970 г. плюс 100 000 000 000 миллисекунд приблизительно равно 3 марта 1973 г.:
Пример
01 января 1970 г. минус 100 000 000 000 миллисекунд примерно 31 октября 1966 г.:
Пример
Пример
Один день (24 часа) — 86 400 000 миллисекунд.
Методы даты
Когда создается объект Date, с ним можно работать с помощью ряда методов.
Методы даты позволяют получать и устанавливать год, месяц, день, час, минуту, секунду и миллисекунду объектов даты, используя либо местное время, либо время UTC (универсальное или GMT).
Методы даты и часовые пояса рассматриваются в следующих главах.
Отображение дат
JavaScript (по умолчанию) выводит даты в формате полнотекстовой строки:
Когда вы отображаете объект даты в HTML, он автоматически преобразуется в строку с помощью метода toString() .
Пример
Same as:
Метод toUTCString() преобразует дату в строку UTC (стандарт отображения даты).
Пример
Метод toDateString() преобразует дату в более читаемый формат:
Пример
Метод toISOString() преобразует объект Date в строку, используя стандартный формат ISO:
Пример
ПАЛИТРА ЦВЕТОВ
ПРИСОЕДИНЯЙТЕСЬ!
Связь с админом
Если вы хотите сообщить об ошибке, а также внести предложение о работе сайта, добавить объявление или рекламу на сайт, не стесняйтесь отправить админу электронное письмо на email:
Топ Учебники
Топ Справочники
Топ Примеры
Веб Сертификаты
Этот сайт оптимизирован для обучения и тестирования. Примеры могут быть упрощены для улучшения чтения и базового понимания. Учебные пособия, ссылки и примеры постоянно пересматриваются, чтобы избежать ошибок, но мы не можем гарантировать полную правильность и работоспособность всего контента. Используя этот сайт, вы соглашаетесь с тем, что прочитали и приняли условия использования, cookie и политику конфиденциальности.
Также вы можете абсолютно бесплатно скачать офлайн версию сайта W3Schools на русском архивом с GitHub и пользоваться локально на своём компьютере.
Также доступна версия сайта W3Schools на украинском языке.
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.
Сайт работает на фреймворке W3.CSS.Работа с датой и временем в JavaScript. Объект класса Date. Полная инструкция

JavaScript
В этом уроке уроке рассмотрим работу с датой и временем в JavaScript. Как создавать текущую дату, вывод времени в JS: как получить год, месяц, дату, часы и минуты.
— Как отформатировать время в JS.
— Что такое UTC и GMT.
— Как форматировать время с помощью toLocaleDateString(),
— В чем передавать дату и время через Fetch,
— метод toISOString().Приглашаю к просмотру видео урока или посмотреть его текстовую версию ниже.
Создание времени
Чтобы создать объект даты и времени, достаточно воспользоваться классом Date. При создании нового объекта времени — создается объект с текущей датой и временем.
Создать текущее время и дату:
Также при создании объекта Date можно передать набор аргументов — год, месяц (0 — Январь, 11 — Декабрь), число, часы, минуты, секунды, миллисекунды.
Также можно передать дату и время ы более свободном формате, в виде строки. При этом конструктор постарается распарсить строчку чтобы понять указанную в ней дату и время:
Еще создать дату можно на основе временной метки timestamp:
И на основе ISO строки:
Форматирование времени. Метод toLocaleString()
Самый простой и быстрый способ вывести отформатированную дату и время, отдельно дату или отдельно время — это использовать метод .toLocaleString()
Получение timeStamp временной метки в милисекундах
Получение отдельных компонентов времени
С помощью специальных методов мы можем получать отдельные компоненты даты и времени. Можно получить год, месяц, часы, минуты, секунды, миллисекунды.
Собственная функция форматирования времени
Получение отдельных компонентов времени может пригодится вам для написания собственных функций форматирования времени.
Напишем функцию чтобы получать время в формате 24.01.2022, 14:15
На основе предыдущей функции, напишем ещё одну, которая будет выводить время в формате Напишем функцию чтобы получать время в формате Пн, 24 января 2022, 16:12
Изменение отдельных компонентов времени
С помощью специальных методов мы можем изменять отдельные компоненты даты и времени. Можно менять год, месяц, часы, минуты, секунды, миллисекунды.
Также можно более точно указывать часы, минуты и секунды:
Автоисправление. Добавление времени
При работе с датой и временем объект Date умеет делать автоисправление. Например если мы указали количество часов больше чем 24, то «лишние» часы не пропадут а перейдут на другой день и дата увеличится на 1 день.
Благодаря этому можно делать добавление времени, например указать сколько нужно добавить «часов» к текущему времени:
Сравнение времени
Чтобы сравнить время в двух объектах типа Date, необходимо сравнивать не сами объекты, а их timestamp:
Разность времени
Можно узнать разность дат и времени. Для этого необходимо получить временные метки для обоих дат:
Временная метка timestamp
Timestamp (временная метка) — это целое число равное количеству милисекунд (внимание, в UNIX timestamp исчисляется в секундах), прошедших с полуночи 1 января 1970 года по усреднённому времени Гринвича (т.е. нулевой часовой пояс, точка отсчёта часовых поясов) GMT 0 / UTC 0.
Получить timestamp можно вызвав метод .getTime() на любом объекте класса Date:
Можно использовать timestamp при создании новой даты:
Также на существующем объекте с датой, можно полностью заменить его дату и время вызвав метод setTime() :
Международное время и часовые пояса. UTC и GMT форматы
Рекомендую замечательную статью чтобы узнать про форматы времени, GMT и UTC: https://raznisa.ru/raznica-mezhdu-gmt-i-utc/
Если очень вкратце, то вот несколько тезисов которые вам надо знать о форматах GMT и UTC:
GMT — основано на астрономических наблюдениях
UTC — метод измерения времени с использованием атомных часов
Разница во времени между UTC и GMT составляет доли секунды. Поэтому для общих целей оба времени считаются одинаковыми.
Грубо говоря, мы можем сказать что: UTC = GMT = UTC+0 = GMT+0
Поэтому если где-то вы встречаете формулировку «время по UTC» — то здесь имеется ввиду UTC+0, просто +0 не уточняется.
Хранение времени внутри объектов класса Date
Внутри объектов Date время всегда хранится в виде временной метки Timestamp. Timestamp всегда описывает время по часовому поясу UTC+0.
При выводе времени (например распечатка в консоль), происходит автоматическое форматирование времени в текущий часовой пояс.
Чтобы пояснить, сделаем следующий пример. Создадим время по временной метке 0, то есть ноль секунд прошедших с 1 января 1970 года. При попытке вывода этого времени находясь в часовом поясе GMT+3 (Москва) мы увидим 03:00 часа, потому как GMT+3 имеет разницу в 3 часа по сравнению с UTC+0.
Еще пример, создадим время по timestamp равному 1 час с 1970 года:
Получим 1 час в UTC+0, и 4 часа при выводе, так как локальное время в браузере GMT+3.
Также мы всегда можем узнать на сколько наша локальная временная зона отличается от зоны UTC+0, для этого есть метод d.getTimezoneOffset() . Он возвращает количество минут на сколько отличается зона UTC от вашей локальной зоны. Запустив его находясь в Москве GMT+3 получим -180 минут.
Международный ISO формат. Метод toISOString()
Существует международный ISO формат времени, выглядит следующим образом: 2022-01-01T07:15:00.000Z Сначала идет дата, после разделитель T , далее время часы, минуты, секунды, и после точки . милисекунды, в конце буква Z . Буква Z означает что время указано в UTC (UTC+0).
Чтобы получить ISO формат времени, необходимо вызвать метод .toISOString();
На основе ISO строки можно создать объект Date:
При конвертации объекта типа Date в JSON строку он автоматически конвертируется в ISOString:
Если сравним, то получим true:
Поэтому можно смело конвертировать объект Date в JSON и сохранять в localStorage или передавать через fetch в API.