How to Create a Date without Timezone in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 6, 2024
2 min

banner

# Create a Date without Timezone using JavaScript

To create a date without timezone:

  1. Get the ISO representation of the date string.
  2. Remove the Z character from the end of the ISO string.
  3. Pass the result to the Date() constructor.
index.js
const dateStr = '2022-07-21T09:35:31.820Z'; const date = new Date(dateStr); console.log(date); // ๐Ÿ‘‰๏ธ Thu Jul 21 2022 12:35:31 GMT+0300 const result = new Date(date.toISOString().slice(0, -1)); console.log(result); // ๐Ÿ‘‰๏ธ Thu Jul 21 2022 09:35:31 GMT+0300

create date without timezone

The code for this article is available on GitHub

We passed the date string to the Date() constructor to get a Date object.

The time in the date string is 09:35:31, whereas the time in the Date object shows 12:35:31. This is because my time zone is 3 hours ahead of Coordinated Universal time (UTC).

To create a Date without the timezone, we called the toISOString() method on the Date object and removed the character Z from the ISO string.

The Date object shows the exact same time as the one stored in the dateStr variable - 09:35:31.

The toISOString method returns an ISO 8601 formatted string that represents the given date.

index.js
const dateStr = '2022-07-21T09:35:31.820Z'; const date = new Date(dateStr); console.log(date); // ๐Ÿ‘‰๏ธ Thu Jul 21 2022 12:35:31 GMT+0300 // ๐Ÿ‘‡๏ธ "2022-07-21T09:35:31.820Z" console.log(date.toISOString());

using toisostring method

The code for this article is available on GitHub

The ISO string is formatted as YYYY-MM-DDTHH:mm:ss.sssZ.

If the Z is present, the Date is set to UTC. If the Z is not present, it's set to local time (this only applies if the time is provided).

The Z at the end of the ISO string means UTC, in other words, an offset from UTC of zero hours, minutes and seconds.

# 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.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev