skip to Main Content

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


  1. To convert a local date and time displayed on a webpage to UTC in JavaScript, you can use the following steps:

    1. Get the local date and time from the webpage.
    2. Use Date.parse() or new Date() to create a Date object from the local date and time string.
    3. Once you have the Date object, you can use the 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:

    // Get the local date and time from the webpage
    const localDateAndTime = "Feb 12, 2024 5:12 PM";
    
    // Create a Date object from the local date and time
    const localDateObject = new Date(localDateAndTime);
    
    // Get the timestamp for the local date and time in UTC
    const utcTimestamp = localDateObject.getTime();
    
    // Display the UTC timestamp
    console.log(utcTimestamp);
    

    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.

    Login or Signup to reply.
  2. 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());

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search