Search code examples
javascriptmomentjstampermonkey

Convert Text to Integer in JS


I am trying to use Tampermonkey to find a UTC time offset and return it as as a time. The website shows an offset which I pull here

waitForKeyElements (".UTCText", getTZ_Offset); 

which returns a string

console.log ("Found timezone offset: ", tzOffset);

usually like this 08:00 It can be + or -

Then i want to convert that into actual time. Eg if UTC time is 00:00, I would like to print a string "The users time is 08:00" if the offset was +08:00.

I thought i could use momentjs to get UTC time moment().utcOffset(tzOffset) and pass the offset.

When i do that it just returns NaN

What am I doing wrong?


Solution

  • Multiply the part before the : by 60, and add it to the second part:

    const tzOffset = '08:00';
    const [hourOffset, minuteOffset] = tzOffset.split(':').map(Number);
    
    const totalMinuteOffset = hourOffset * 60 + minuteOffset;
    console.log(totalMinuteOffset);

    If the input may be negative, then check that as well:

    const tzOffset = '-08:00';
    const [_, neg, hourOffset, minuteOffset] = tzOffset.match(/(-)?(\d{2}):(\d{2})/);
    
    const totalMinuteOffset = (neg ? -1 : 1) * (hourOffset * 60 + Number(minuteOffset));
    console.log(totalMinuteOffset);

    A few time zones differ from UTC not only by hours, but by minutes as well (eg, UTC +5:30, UTC +9:30), so just parseInt, even if it worked, wouldn't be reliable everywhere.