1/* 2 * Copyright (C) 2022 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 17export const INVALID_TIME_NS = 0n; 18 19export class TimeRange { 20 constructor(readonly from: Timestamp, readonly to: Timestamp) {} 21 22 containsTimestamp(ts: Timestamp): boolean { 23 const min = this.from.getValueNs(); 24 const max = this.to.getValueNs(); 25 return ts.getValueNs() >= min && ts.getValueNs() <= max; 26 } 27} 28 29export interface TimezoneInfo { 30 timezone: string; 31 locale: string; 32} 33 34export interface TimestampFormatter { 35 format(timestamp: Timestamp): string; 36} 37 38export class Timestamp { 39 private readonly utcValueNs: bigint; 40 private readonly formatter: TimestampFormatter; 41 42 constructor(valueNs: bigint, formatter: TimestampFormatter) { 43 this.utcValueNs = valueNs; 44 this.formatter = formatter; 45 } 46 47 getValueNs(): bigint { 48 return this.utcValueNs; 49 } 50 51 valueOf(): bigint { 52 return this.utcValueNs; 53 } 54 55 in(range: TimeRange): boolean { 56 return ( 57 range.from.getValueNs() <= this.getValueNs() && 58 this.getValueNs() <= range.to.getValueNs() 59 ); 60 } 61 62 add(n: bigint): Timestamp { 63 return new Timestamp(this.getValueNs() + n, this.formatter); 64 } 65 66 minus(n: bigint): Timestamp { 67 return new Timestamp(this.getValueNs() - n, this.formatter); 68 } 69 70 times(n: bigint): Timestamp { 71 return new Timestamp(this.getValueNs() * n, this.formatter); 72 } 73 74 div(n: bigint): Timestamp { 75 return new Timestamp(this.getValueNs() / n, this.formatter); 76 } 77 78 format(): string { 79 return this.formatter.format(this); 80 } 81} 82