skip to Main Content

I have input string like 2023-02-02 15:35 CET and I have to convert this into UTC time.

I’m trying to find a solution for this, but I’m not able to figure out how to convert input string into Date() object in js.

My main problem is that I cannot figure out how to create Date() with timezone. Time-zones can differ and it could be anything like BST, HKTect.

Can somebody help how to get UTC time from input string like this?

2

Answers


  1. to convert your date to UTC you can use the .toUTCString() method.

    var inputDate = "2023-02-02 15:35 EST";
    var date = new Date(inputDate);
    var dateUTC = date.toUTCString();
    console.log(dateUTC);
    
    Login or Signup to reply.
  2. I just translated the PHP code from the following thread https://stackoverflow.com/questions/67295211/convert-cest-cet-to-utc0 into javascript. Hope it will work for you

    function convertCESTorCET(dateTime) {
        // Create two timezone objects
        const timeZoneUTC0 = 'Atlantic/Reykjavik';
        const timeZoneCEST_CET = 'Europe/Copenhagen';
    
        // Create two Date objects that will contain the same Unix timestamp, but
        // have different timezones attached to them.
        const dateUTC = new Date(dateTime);
        const dateCEST_CET = new Date(dateTime);
    
        // Set the timezones for the Date objects
        dateUTC.setTimezone(timeZoneUTC0);
        dateCEST_CET.setTimezone(timeZoneCEST_CET);
    
        // Calculate the time offset for the date/time contained in the dateUTC
        // object, but using the timezone rules as defined for Denmark
        // (dateCEST_CET).
        const timeOffset = dateCEST_CET.getTimezoneOffset() * 60 * 1000; // Convert minutes to milliseconds
    
        // Calculate the new timestamp by subtracting the time offset
        const newTimestamp = new Date(dateUTC - timeOffset);
    
        // Format the new timestamp to match the "Y-m-d H:i:s" format
        const formattedDate = newTimestamp.toISOString().replace('T', ' ').substr(0, 19);
    
        return formattedDate;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search