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