Search code examples
javakotlindatedatetime-formatjava-time

converting startDatetime to localtime using UTC timezone


We have a usecase, where we have startDateTime, endDateTime and timeZoneOffset.

timeZoneOffset: UTC-2:30
Here the expected time is mentioned if timezoneOffset is in negative.

current time expected time after UTC adjustment
startDateTime: 2023-07-25T12:40:46.143Z 2023-07-25T10:10:46.143Z
endDateTime: 12023-07-25T12:54:05.558Z 2023-07-25T10:24:05.558Z

timeZoneOffset: UTC+2:30
Here the expected time is mentioned if timezoneOffset is in positive.

current time expected time after UTC adjustment
2023-07-25T12:43:05.558Z 2023-07-25T15:10:05.558Z
2023-07-25T12:54:05.558Z 2023-07-25T15:24:05.558Z

We are looking for methods in LocalDateTime, ZoneOffSet. But we did not find the methods which we can use to get the expected time.

Can someone please suggest what libraries we can use in Java/Kotlin to get the expected result.

I am expecting the output in DateTime format after adjusting with the UTC value. We wanted to convert the DateTime in local-time.

We have below code snippets for your reference:

    var timeZoneOffset: String? = null
    timeZoneOffset: "UTC-08:00"
    

    var startDateTime: LocalDateTime? = null
     startDateTime: 2023-07-25T12:40:46.143Z


    var endDateTime: LocalDateTime? = null
    endDateTime: 2023-07-25T12:43:05.558Z

Solution

  • This is for time zone only, refer to Basil's answers for offset

    Not quite sure why you represent 2023-07-25T12:54:05.558Z in LocalDateTime, as Z indicate UTC+0, so it should be ZonedDateTime instead.

    Base on the given example, what you are trying is like

    1. Given a input at UTC+0, find the equivalent time at given zone offset
    2. Change the zone back to UTC+0 without changing the time

    And it could be done using:

    Below demonstrate how to implement such adjustment in kotlin.

    import java.time.ZoneOffset
    import java.time.ZonedDateTime
    
    fun main() {
        val timeZoneOffset = "UTC-02:30"
    
        val zoneOffset = ZoneOffset.of(timeZoneOffset.replace("UTC", ""))
    
        val startDateTime: ZonedDateTime = ZonedDateTime.parse("2023-07-25T12:40:46.143Z")
        println(adjustZone(startDateTime, zoneOffset))
    
        val endDateTime: ZonedDateTime = ZonedDateTime.parse("2023-07-25T12:43:05.558Z")
        println(adjustZone(endDateTime, zoneOffset))
    }
    
    fun adjustZone(zonedDateTime: ZonedDateTime, zoneOffset: ZoneOffset)
            : ZonedDateTime {
        return zonedDateTime
            .withZoneSameInstant(zoneOffset)
            .withZoneSameLocal(zonedDateTime.zone)
    }