Home > database >  How to change timezone of date android kotlin [HH:mm]
How to change timezone of date android kotlin [HH:mm]

Time:12-15

As input, I get a string like HH:mm, which is UTC. But I need to convert the time to 3 hours (i.e. UTC 3).

For example, it was 12:30 - it became 15:30.

I tried this code, but its not working :(

fun String.formatDateTime(): String {
    val sourceFormat = SimpleDateFormat("HH:mm", Locale.getDefault())
    sourceFormat.timeZone = TimeZone.getTimeZone("UTC")
    val parsed = sourceFormat.parse(this)

    val tz = TimeZone.getTimeZone("UTC 3")
    val destFormat = SimpleDateFormat("HH:mm", Locale.getDefault())
    destFormat.timeZone = tz

    return parsed?.let { destFormat.format(it) }.toString()
}

How can i do this?

CodePudding user response:

        @SuppressLint("SimpleDateFormat")
    fun getDayOfWeekOfMonthDateFormat(timeZone: String? = "GMT"): SimpleDateFormat {
        val format = SimpleDateFormat("MMMM EEEE dd")
        timeZone?.let {
            format.timeZone = TimeZone.getTimeZone(it)
        }
        return format
    }

This is function for returning "GMT" as default and if you wanna change,  add "GMT 5:30"

NB: change the format with your requirement 

CodePudding user response:

You can use java.time for this and if you just want to add a specific amount of hours, you can use LocalTime.parse(String), LocalTime.plusHours(Long) and DateTimeFormatter.ofPattern("HH:mm"). Here's a small example:

import java.time.LocalTime
import java.time.format.DateTimeFormatter

fun String.formatDateTime(hoursToAdd: Long): String {
    val utcTime = LocalTime.parse(this)
    val targetOffsetTime = utcTime.plusHours(hoursToAdd)
    return targetOffsetTime.format(DateTimeFormatter.ofPattern("HH:mm"))
}

fun main() {
    println("12:30".formatDateTime(3))
}

Output is simply 15:30.

Try it with "22:30" and you'll get "01:30" as output.

Please note that daylight saving time may cause problems if you are not supposed to just add three hours but consider a real time zone whose offset from UTC may change.

CodePudding user response:

java.time

The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API.

Solution using java.time API

Parse the given time string using LocalTime#parse and then convert it into a UTC OffsetTime by using LocalTime#atOffset. The final step is to convert this UTC OffsetTime into an OffsetTime at the offset of 03:00 which you can do by using OffsetTime#withOffsetSameInstant.

Note that you do not need a DateTimeFormatter to parse your time string as it is already in ISO 8601 format, which is the default format that is used by java.time types.

Demo:

class Main {
    public static void main(String args[]) {
        String sampleTime = "12:30";
        OffsetTime offsetTime = LocalTime.parse(sampleTime)
                .atOffset(ZoneOffset.UTC)
                .withOffsetSameInstant(ZoneOffset.of(" 03:00"));
        System.out.println(offsetTime);

        // Gettting LocalTine from OffsetTime
        LocalTime result = offsetTime.toLocalTime();
        System.out.println(result);
    }
}

Output:

15:30 03:00
15:30

Online Demo

Learn more about the modern Date-Time API from Trail: Date Time.

  • Related