Create a Date without Timezone using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

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

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());

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.

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.