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, type: TimestampFormatType): string; 36} 37 38export enum TimestampFormatType { 39 FULL, 40 DROP_DATE, 41} 42 43export class Timestamp { 44 private readonly utcValueNs: bigint; 45 private readonly formatter: TimestampFormatter; 46 47 constructor(valueNs: bigint, formatter: TimestampFormatter) { 48 this.utcValueNs = valueNs; 49 this.formatter = formatter; 50 } 51 52 getValueNs(): bigint { 53 return this.utcValueNs; 54 } 55 56 valueOf(): bigint { 57 return this.utcValueNs; 58 } 59 60 in(range: TimeRange): boolean { 61 return ( 62 range.from.getValueNs() <= this.getValueNs() && 63 this.getValueNs() <= range.to.getValueNs() 64 ); 65 } 66 67 add(n: bigint): Timestamp { 68 return new Timestamp(this.getValueNs() + n, this.formatter); 69 } 70 71 minus(n: bigint): Timestamp { 72 return new Timestamp(this.getValueNs() - n, this.formatter); 73 } 74 75 times(n: bigint): Timestamp { 76 return new Timestamp(this.getValueNs() * n, this.formatter); 77 } 78 79 div(n: bigint): Timestamp { 80 return new Timestamp(this.getValueNs() / n, this.formatter); 81 } 82 83 format(type = TimestampFormatType.FULL): string { 84 return this.formatter.format(this, type); 85 } 86} 87