time.kt (1856B)
1 /* 2 * This file is part of LibEuFin. 3 * Copyright (C) 2024 Taler Systems S.A. 4 5 * LibEuFin is free software; you can redistribute it and/or modify 6 * it under the terms of the GNU Affero General Public License as 7 * published by the Free Software Foundation; either version 3, or 8 * (at your option) any later version. 9 10 * LibEuFin is distributed in the hope that it will be useful, but 11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General 13 * Public License for more details. 14 15 * You should have received a copy of the GNU Affero General Public 16 * License along with LibEuFin; see the file COPYING. If not, see 17 * <http://www.gnu.org/licenses/> 18 */ 19 20 package tech.libeufin.common 21 22 import org.slf4j.Logger 23 import org.slf4j.LoggerFactory 24 import java.time.Instant 25 import java.time.temporal.ChronoUnit 26 27 private val logger: Logger = LoggerFactory.getLogger("libeufin-common") 28 29 /** 30 * Convert Instant to microseconds since the epoch. 31 * 32 * Returns Long.MAX_VALUE if instant is Instant.MAX 33 **/ 34 fun Instant.micros(): Long { 35 if (this == Instant.MAX) 36 return Long.MAX_VALUE 37 try { 38 val micros = ChronoUnit.MICROS.between(Instant.EPOCH, this) 39 if (micros == Long.MAX_VALUE) throw ArithmeticException() 40 return micros 41 } catch (e: ArithmeticException) { 42 throw Exception("$this is too big to be converted to micros resolution", e) 43 } 44 } 45 46 /** 47 * Convert microsecons to Instant. 48 * 49 * Returns Instant.MAX if microseconds is Long.MAX_VALUE 50 */ 51 fun Long.asInstant(): Instant { 52 if (this == Long.MAX_VALUE) 53 return Instant.MAX 54 return try { 55 Instant.EPOCH.plus(this, ChronoUnit.MICROS) 56 } catch (e: ArithmeticException ) { 57 throw Exception("$this is too big to be converted to Instant", e) 58 } 59 }