Home > front end >  How to identify timezone by string time and convert multiple timezones to one timezone in kotlin
How to identify timezone by string time and convert multiple timezones to one timezone in kotlin

Time:01-30

I have list of records with dateTime in different timezones

[
    {
        "id": 1,
        "dateTime": "2023-01-01T14:10:24.478Z"
    },
    {
        "id": 2,
        "dateTime": "2023-01-22T08:39:48.374 08:00"
    }.
    {
        "id": 3,
        "dateTime": "2023-01-22T08:39:48.374 05:30"
    }
]

data class Record(val id: Int, val dateTime: String)

I need to convert these all dateTime to my timezone (Eg: 04:00)

Is there a best way to identify timezone by dateTime value to convert it to my timezone? or do we need substring dateTime and find timezone value add custom method to get timezone?

Eg:

fun String.timezone() : String? {
    return when(this) {
        " 05:30" -> "Asia/Calcutta"
        "Z" -> "UTC"
            .....
        else -> null
    }
}

(I know how to convert dateTime to my tomezone if know tomezone of dateTime)

CodePudding user response:

Are you asking how to map an offset to a time zone? You cannot. At any moment, several time zones can share coincidentally share the same offset.

You said:

my timezone (Eg: 04:00)

Correction… Your example 04:00 is an offset from UTC, not a time zone.

An offset is merely a number of hours-minutes-seconds ahead or behind the temporal prime meridian of UTC. In Java, use ZoneOffset with OffsetDateTime.

A time zone is a named history of the past, present, and future changes to the offset used by the people of a particular region, as decided by their politicians. In Java, use ZoneId with ZonedDateTime.

Point on timeline
Offset from UTC ZoneOffset OffsetDateTime
Time zone ZoneId ZonedDateTime

A time zone has a name in the format of Continent/Region. For example, Africa/Casablanca or Pacific/Auckland. FYI, the time zone Asia/Calcutta has been renamed Asia/Kolkata.

Parse your inputs as OffsetDateTime objects.

(Java syntax; I don’t know Kotlin)

OffsetDateTime odt = OffsetDateTime.parse( "2023-01-22T08:39:48.374 08:00" ) ;

Apply your desired time zone.

ZoneId z = ZoneId.of( "Asia/Dubai" ) ;
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;
  • Related