- Javascript date now in utc
- # Table of Contents
- # Get the current Date and Time in UTC/GMT using JavaScript
- # Get the current Date and Time in UTC/GMT using toISOString()
- # Get a GMT/UTC Date or convert a Date to GMT/UTC in JavaScript
- # Additional Resources
- Date.now()
- Синтаксис
- Параметры
- Описание
- Полифил
- Спецификации
- Совместимость с браузерами
- Смотрите также
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
Javascript date now in utc
Last updated: Jan 12, 2023
Reading time · 5 min
# Table of Contents
# Get the current Date and Time in UTC/GMT using JavaScript
Use the toUTCString() method to get the current date and time in UTC/GMT, e.g. new Date().toUTCString() .
The method converts the date to a string, using the UTC time zone, which shares the same current time with GMT.
Copied!const utcStr = new Date().toUTCString(); console.log(utcStr); // 👉️ "Mon, 24 Jul 2023 16:46:35 GMT" const isoStr = new Date().toISOString(); console.log(isoStr); // 👉️ "2023-07-24T16:46:35.269Z"
The toUTCString method returns a string that represents the date using the UTC time zone.
# Get the current Date and Time in UTC/GMT using toISOString()
You could also use the toISOString() method to get a string in the ISO 8601 format of YYYY-MM-DDTHH:mm:ss.sssZ .
The Z at the end of the format means UTC, that is, an offset from UTC of zero hours, minutes and seconds.
Copied!const isoStr = new Date().toISOString(); console.log(isoStr); // 👉️ "2023-07-24T16:47:57.673Z"
The toISOString method returns a string representing the date in the ISO 8601 format, according to universal time.
You can also use the available getUTC* methods that return the date and time components according to universal time.
They are quite useful and enable us to format the date and time in many different ways, using string concatenation.
Copied!const date = new Date(); // 👉️ "Sat Jan 15 2022 18:23:51 GMT+0200" console.log(date); // 👇️ returns UTC year of the date console.log(date.getUTCFullYear()); // 👉️ 2022 // 👇️ returns UTC month (0-11) // 0 is January, 11 is December console.log(date.getUTCMonth()); // 👉️ 0 // 👇️ returns UTC day of the month (1-31) console.log(date.getUTCDate()); // 👉️ 15 // 👇️ returns UTC Hour of the date console.log(date.getUTCHours()); // 👉️ 16 // 👇️ returns UTC Minutes of the date console.log(date.getUTCMinutes()); // 👉️ 23 // 👇️ returns UTC Seconds of the date console.log(date.getUTCSeconds()); // 👉️ 51
All of the getUTC* methods return the date or time component according to universal time.
Note that the getUTCMonth method returns the month of the specified date as a zero-based value (0 = January, 1 = February, etc.)
Here is an example that uses the getUTC* methods to format a Date as YYYY-MM-DD hh:mm:ss .
Copied!function padTo2Digits(num) return num.toString().padStart(2, '0'); > function formatDate(date) return ( [ date.getFullYear(), padTo2Digits(date.getUTCMonth() + 1), padTo2Digits(date.getUTCDate()), ].join('-') + ' ' + [ padTo2Digits(date.getUTCHours()), padTo2Digits(date.getUTCMinutes()), padTo2Digits(date.getUTCSeconds()), ].join(':') ); > // 👇️ "2022-01-15 16:25:12" console.log(formatDate(new Date()));
We created a reusable function that formats the date and time as YYYY-MM-DD hh:mm:ss using the UTC time standard.
You could reorder the date components, change the separator to a forward slash / , or make any other changes that suit your use case.
# Get a GMT/UTC Date or convert a Date to GMT/UTC in JavaScript
You can also use the toUTCString() method to get a UTC/GMT date set to a different time.
The method converts the date to a string, using the UTC time zone, which shares the same current time with GMT.
Copied!// ✅ (Optionally) Create a Date using Universal time (= GMT) // instead of local time const d1 = new Date(Date.UTC(2022, 0, 14, 14, 30, 0)); console.log(d1); // -------------------------------------------- // ✅ Get a String representing the given Date // using UTC (= GMT) time zone. const d2 = new Date(); const result = d2.toUTCString(); console.log(result); // 👉️ "Fri, 14 Jan 2022 16:50:03 GMT" // 👇️ returns UTC (=GMT) Hour of the date console.log(d2.getUTCHours()); // 👉️ 16 // 👇️ returns UTC (=GMT) Minutes of the date console.log(d2.getUTCMinutes()); // 👉️ 50 // 👇️ returns UTC (=GMT) Seconds of the date console.log(d2.getUTCSeconds()); // 👉️ 03
The difference between them is that GMT is a time zone, whereas UTC is a time standard and is the basis for time zones worldwide.
In the first example, we used the Date.UTC method, which treats the passed-in parameters as UTC.
Copied!const d1 = new Date(Date.UTC(2022, 0, 14, 14, 30, 0)); console.log(d1); // 👉️ 2022-01-14T14:30:00.000Z
We used this approach to create a date object that has its time set according to GMT and not local time (the visitor’s computer time zone).
The parameters we passed to the Date.UTC method are the year , month (0 — 11), day , hour , minute , second .
In the second example, we used the toUTCString method to get the GMT/UTC representation of the date.
Copied!const d2 = new Date(); const result = d2.toUTCString(); console.log(result); // 👉️ "Fri, 14 Jan 2022 16:50:03 GMT"
The method converts the date to a string, using the UTC time zone, which shares the same current time with GMT.
You can also use the available getUTC* methods that return the date and time components according to universal time (= GMT).
Copied!const d2 = new Date(); const result = d2.toUTCString(); console.log(result); // 👉️ "Fri, 14 Jan 2022 16:50:03 GMT" // 👇️ returns UTC (=GMT) Hour of the date console.log(d2.getUTCHours()); // 👉️ 16 // 👇️ returns UTC (=GMT) Minutes of the date console.log(d2.getUTCMinutes()); // 👉️ 50 // 👇️ returns UTC (=GMT) Seconds of the date console.log(d2.getUTCSeconds()); // 👉️ 03 // 👇️ returns UTC (=GMT) year of the date console.log(d2.getUTCFullYear()); // 👉️ 2022 // 👇️ returns UTC (=GMT) month (0-11) // 0 is January, 11 is December console.log(d2.getUTCMonth()); // 👉️ 0 // 👇️ returns UTC (=GMT) day of the month (1-31) console.log(d2.getUTCDate()); // 👉️ 14
All of the getUTC* methods return the date or time component according to universal time (= GMT).
Copied!const date = new Date(); console.log( [ padTo2Digits(date.getUTCHours()), padTo2Digits(date.getUTCMinutes()), padTo2Digits(date.getUTCSeconds()) ].join(':') ); // 👉️ "17:30:20" (hh:mm:ss) function padTo2Digits(num) return num.toString().padStart(2, '0'); >
Note that the getUTCMonth method returns the month of the specified date as a zero-based value (0 = January, 1 = February, etc.)
You can view all of the getUTC methods by visiting the MDN docs.
There is a non-UTC equivalent for each of these methods, for example getUTCFullYear vs Date.getFullYear.
The getUTC* methods return the date or time component according to universal time (= GMT), whereas the get* methods return them according to local time (the time zone the visitor’s computer is in).
The get* methods return different results depending on where the user visits your site from.
For example, if you store a local time of midnight (00:00) in your database, you wouldn’t know if that’s midnight in Tokyo (Japan), Paris (France), in New York (US), etc. These are all different moments that are hours apart.
For consistency, you should mostly use local time when you have to render a date and time to the user, but store the actual values in UTC (=GMT).
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
Date.now()
Метод Date.now() возвращает количество миллисекунд, прошедших с 1 января 1970 года 00:00:00 по UTC.
Синтаксис
Параметры
Описание
Метод now() возвращает количество миллисекунд, прошедших с 1 января 1970 года 00:00:00 по UTC по текущий момент времени в качестве числа.
Поскольку метод now() является статическим методом объекта Date , вы всегда должны использовать его как Date.now() .
Полифил
Этот метод был стандартизирован в ECMA-262 5-го издания. Отсутствие этого метода в движках, которые не были обновлены для его поддержки, можно обойти следующей прокладкой:
if (!Date.now) Date.now = function now() return new Date().getTime(); >; >
Спецификации
Совместимость с браузерами
BCD tables only load in the browser
Смотрите также
- Performance.now() — предоставляет временные метки с разрешением в доли миллисекунд для использования при измерении производительности веб-страницы
- console.time() / console.timeEnd()
Found a content problem with this page?
This page was last modified on 7 нояб. 2022 г. by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.