0

I'm trying to write a Kotlin function which replicates the behaviour of fromNow in the moment library.

I have the following code:

fun formatDuration(dateTime: String): String {
    try {
        val parsedDateTime = Instant.parse(dateTime)
        val prettyTime = PrettyTime()
        prettyTime.reference = Instant.now().atZone(ZoneOffset.UTC).toInstant()
        return prettyTime.format(parsedDateTime)
    } catch (e: DateTimeParseException) {
        e.printStackTrace()
        return "Invalid date/time format"
    }
}

The problem is when the device time is 9:44 and the input string is 2023-02-19T11:48:09.958Z, and the current UTC time is 15:19 it will output 2 hours from now, even though it should output 3 hours ago like the moment function does as the timestamp is in UTC.

How can I fix this to always take into account UTC time not local time when calculating the difference?

Alk
  • 5,215
  • 8
  • 47
  • 116

1 Answers1

0

Have you tried to change:

from:

val parsedDateTime = Instant.parse(dateTime)

to:

val parsedDateTime = Instant.parse(dateTime).atZone(ZoneOffset.UTC).toInstant()