I’m experimenting with Javascript, and wanted to try out converting a date and time that is indicating when the post was posted (such as a social media site), which is the local time zone (so if my system is EST, the page will show it as EST). I would like to have JS to also know what time zone my PC is at, then take the shown post date (assume its post date is the same as my PC), and convert it to UTC. I understand toISOString, the milliseconds since the epoch work. But how do I convert a local date and time displayed on a webpage to UTC?
Here’s an example: https://bsky.app/profile/kimscaravelli.bsky.social/post/3klaue65stp2x
The post date from my PC at my time zone says in EST – "Feb 12, 2024 at 5:12 PM". However it may be different when you guys view the post date. I’m also aware of the daylight savings time does effect several time zones, but UTC and the milliseconds since the epoch are unaffected. I do not want to manually have to set my PC or website settings to make the site display the UTC time, instead I wanted JS code that regardless of what time zone you are in, a post that displays a date locally, it will always display the same UTC time.
2
Answers
To convert a local date and time displayed on a webpage to UTC in JavaScript, you can use the following steps:
Date.parse()
ornew Date()
to create a Date object from the local date and time string.getTime()
method to get the timestamp (in milliseconds since the epoch) for that date and time in UTC.Here’s an example of how you can achieve this in JavaScript:
By following these steps, you will be able to obtain the UTC timestamp for the given local date and time, regardless of the time zone of the user viewing the webpage.
var date = new Date();
var now_utc = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
console.log(new Date(now_utc));
console.log(date.toISOString());