简体   繁体   中英

How do I deal with UTC offset for datetime for the few time zones that are 0.5 rather than whole number

I am trying to deal with time expressed as 2022-07-15 06:30 LT (UTC +5.5) I can work with all the whole number UTC but I haven't found a way to deal with the 0.5

                const date1 = " 2022-07-15 06:30 LT  (UTC +5.5)";
                utcDrop = date1.trim().split("(UTC ")[1].split(")")[0]*1;
                str1 = date1.trim().split(" ")[0];
                str2 = date1.trim().split(" ")[1];
                date3 = str1 + "T" + str2;
                const date = new Date(date3)
                numOfHours = date1.split("UTC ")[1].split(")")[0]*1;
                function subtractHours(numOfHours, date = new Date()) {
                  date.setHours(date.getHours() - numOfHours);
                  
                  return date;
                }
                d=subtractHours(numOfHours, date);
                last_port_atd = d.toISOString().slice(0, 10) + ' ' + d.toTimeString().slice(0, 5);

'2022-07-15 00:30' which is wrong because I do not know the correct statement.

No idea which methods are generally employed for the task, here's a break-down of how I'd go about it.

  1. I'll assume that your string will always contain a UTC offset
  2. I'll assume the offset can be negative, zero or positive
  • there may or may not be whitespace between UTC and the number
  1. We'll capture fractional hours.

I would simply try the parseFloat method on the part of the string I believe to contain the number of interest. I'd use some string searching to locate this number of interest.

 let haystack = '2022-07-15 06:30 LT (UTC -5.5)'; let needle = "UTC"; // set numPos to the index of the char between "UTC" and "-5.5" (a space) let numPos = haystack.indexOf(needle) + needle.length; // extract all chars from this point until the end of the string let numStr = haystack.substr(numPos); // use parseFloat, so we can capture both positive & negative offsets of non-integer amounts let offset = parseFloat(numStr); console.log(offset);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM