DEV Community

Cover image for How to get the current date time of other countries in JavaScript
Dhairya Shah
Dhairya Shah

Posted on • Originally published at dhairyashah.dev

How to get the current date time of other countries in JavaScript

In our interconnected world, being aware of the date and time in other countries is crucial. Luckily, Javascript offers a simple solution for accessing this information. In this article, we'll demonstrate how to use Javascript to obtain the current date and time in other countries.

In this article, I will be using the USA as an example. So, let's get started!

Step: 1 Create a new date object

The first step is to create a new Date Object. This new date object will represent the current date and time of your local timezone.

const d = new Date();
Enter fullscreen mode Exit fullscreen mode

Step: 2 Get local time and offset

Next, we need to get the local time and offset of the current date and time in the local timezone.

What is the local time in Javascript?

The local time is the number of milliseconds since 1st January 1970 (UTC). The offset is the difference between the local time and UTC time.

const localTime = d.getTime();
const localOffset = d.getTimezoneOffset() * 60000;
Enter fullscreen mode Exit fullscreen mode

Step 3: Calculate the UTC time

Now, we need to calculate the UTC time by adding the local time and the time offset.

const utc = localTime + localOffset;
Enter fullscreen mode Exit fullscreen mode

Step: 4 Calculate the time for the country

Now, we can calculate the time for the country by adding the UTC time and the offset together.

const offset = -5; // UTC of USA Eastern Time Zone is -05.00
const usa = utc + (3600000 * offset);
Enter fullscreen mode Exit fullscreen mode

Note: Make sure to change the country offset as per your requirement.

Step: 5 Get the current date and time for the USA

Finally, we can use the new Date() and toLocaleString() methods to get the current date and time for the USA in a human-readable format.

const usaTimeNow = new Date(usa).toLocaleString();
Enter fullscreen mode Exit fullscreen mode

Here's the complete code to get the current date and time of any country in Javascript:

const d = new Date();
const localTime = d.getTime();
const localOffset = d.getTimezoneOffset() * 60000;
const utc = localTime + localOffset;
const offset = -5; // UTC of USA Eastern Time Zone is -05.00
const usa = utc + (3600000 * offset);
const usaTimeNow = new Date(usa).toLocaleString();
console.log(usaTimeNow);
Enter fullscreen mode Exit fullscreen mode

Conclusion

To sum up, you can easily obtain the date and time of any country by solely utilizing Javascript, without relying on external software or APIs.

I hope this article was helpful to you! Thank you for reading.

Cover Image Source: Unsplash

Top comments (0)