1/* 2 * Copyright (C) 2024 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17import {TIME_UNIT_TO_NANO} from './time_units'; 18 19export class UTCOffset { 20 private valueNs: bigint | undefined; 21 22 getValueNs(): bigint | undefined { 23 return this.valueNs; 24 } 25 26 format(): string { 27 if (this.valueNs === undefined) { 28 return 'UTC+00:00'; 29 } 30 const valueHours = Number(this.valueNs / BigInt(TIME_UNIT_TO_NANO.m)) / 60; 31 const valueHoursAbs = Math.abs(valueHours); 32 const hh = Math.floor(valueHoursAbs); 33 const mm = (valueHoursAbs - hh) * 60; 34 const timeDiff = `${hh}`.padStart(2, '0') + ':' + `${mm}`.padStart(2, '0'); 35 return `UTC${this.valueNs < 0 ? '-' : '+'}${timeDiff}`; 36 } 37 38 initialize(valueNs: bigint) { 39 if (valueNs > BigInt(14 * TIME_UNIT_TO_NANO.h)) { 40 console.warn('Failed to set timezone offset greater than UTC+14:00'); 41 return; 42 } 43 if (valueNs < BigInt(-12 * TIME_UNIT_TO_NANO.h)) { 44 console.warn('Failed to set timezone offset greater than UTC-12:00'); 45 return; 46 } 47 this.valueNs = valueNs; 48 } 49 50 clear() { 51 this.valueNs = undefined; 52 } 53} 54