Is there a way to add time to a Timestamp
formatted time without having to convert it multiple times?
val seconds: Long = Timestamp.now().seconds
val utcDT = LocalDateTime.ofEpochSecond(seconds, 0, ZoneOffset.UTC)
val withTwo: LocalDateTime = utcDT.plusHours(2)
val date: Date = Date.from(withTwo.toInstant(ZoneOffset.UTC))
val new = Timestamp(date)
Log.d("sirEgghead", "Timestamp: ${Timestamp.now().toDate()}")
Log.d("sirEgghead", "utcDT: $utcDT")
Log.d("sirEgghead", "addedTwo: $withTwo")
Log.d("sirEgghead", "date: ${date.time}")
Log.d("sirEgghead", "new: ${new.toDate()}")
This is the mess that I went through just to add two hours and return it to Timestamp
format two hours in the future.
Timestamp: Wed May 18 21:53:12 EDT 2022
utcDT: 2022-05-19T01:53:12
addedTwo: 2022-05-19T03:53:12
date: 1652932392000
new: Wed May 18 23:53:12 EDT 2022
I do not want to use the local system time in case the time on the device is incorrect. The data is stored in Google Firestore.
CodePudding user response:
Instead of creating a LocalDateTime
instance, create an Instant
instance and add 2
hours to it, using its plus
method which takes TemporalUnits
for addition.
val seconds: Long = Timestamp.now().seconds
val addedSeconds = Instant.ofEpochSecond(seconds).plus(2, ChronoUnit.HOURS).epochSecond
val newTimeStamp = Timestamp(addedSeconds, 0)