Search code examples
javascriptdatetimetimezonetimezone-offset

How to check if the data time has the timezone offset or not?


I am developing an application using Javascript. Within the code, I am receiving the Datetime. This Datetime can have the timezone offset or not. I would like to check if the timezone offset is present or not based on which I need to make a few decisions.

Following is the type of data that will come into my Javascript function:

const dateWithoutOffset = "2022-03-01T16:23:19"
const dateWithOffset = "2022-03-01T16:23:19+01:00"

//Perform something to check for offset
if(dateWithOffset.contains(offset)){
  console.log("OFFSET is PRESENT")
}

//Perform something to check offset is not present
if(dateWithoutOffset.contains(offset)){
  console.log("OFFSET IS NOT PRESENT")
}

I know that I can check for length but I feel it's not the right way so thought of asking here and finding the right way to find the offset.

I tried a lot of methods and answers present within Stackoverflow but nothing seems to give me the right answer so posting here to get a correct working answer.


Solution

  • You can use regular expressions to parse the offset from these ISO date strings.

    Creating a few convenience functions such as hasOffset() and getUTCOffsetMinutes() should make the problem easier to solve.

    If the date has an offset, you can proceed to parse it (as below) or do something else such as displaying differently.

    const isoDatePattern = /(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}:\d{2})(\.\d+)?([+-]\d{2}:?\d{2}|Z)$/
    
    function getOffsetStr(input) {
        const groups = input.match(isoDatePattern);
        return groups ? groups[4]: null;
    }
    
    function hasOffset(input) {
        return (!!getOffsetStr(input));
    }
    
    function getUTCOffsetMinutes(input) {
        const offset = getOffsetStr(input);
        return offset ? parseUTCOffset(offset): null;
    }
    
    function parseUTCOffset(offsetStr) {
        if (offsetStr.toUpperCase() === 'Z') {
            return 0;
        }
        const sign = offsetStr.startsWith('-') ? -1: 1;
        const hour = +offsetStr.slice(1,3);
        const min = +offsetStr.slice(-2);
        return sign * hour * 60 + min;
    }
    
    const testInputs = [
         "2010-11-06T02:19:00.250",
         "2022-03-01T16:23:19",
         "2025-04-20T17:02:03.401+0200",
         "2022-03-01T16:23:19+01:00",
         "2022-03-01T16:23:19Z",
         "2022-03-01T16:23:19-0500",
         "2022-03-01T16:23:19+12:00"
    ]
    
    console.log('Input'.padEnd(28, ' '), 'Has Offset ' ,'UTC Offset (minutes)')
    testInputs.forEach(input => { 
        console.log(input.padEnd(28, ' '), hasOffset(input), '\t', getUTCOffsetMinutes(input));
    })
    .as-console-wrapper { max-height: 100% !important; }