如何更改日期的时区 android kotlin [HH:mm]

one*_*tor 0 android simpledateformat timezone-offset android-calendar kotlin

作为输入,我得到一个类似 HH:mm 的字符串,它是 UTC。但我需要将时间转换为+3小时(即UTC+3)。

例如,原来是 12:30 - 现在变成了 15:30。

我尝试了这段代码,但它不起作用:(

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()
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Arv*_*ash 5

java.time

日期java.util时间 API 及其格式化 APISimpleDateFormat已经过时且容易出错。建议完全停止使用它们并切换到现代 Date-Time API

使用 java.time API 的解决方案

使用 解析给定的时间字符串,然后使用LocalTime#parse将其转换为 UTC 。最后一步是将此 UTC 转换为您可以使用 进行的偏移量。OffsetTimeLocalTime#atOffsetOffsetTimeOffsetTime+03:00OffsetTime#withOffsetSameInstant

请注意,您不需要 来DateTimeFormatter解析时间字符串,因为它已经采用ISO 8601格式,这是类型使用的默认格式java.time

演示

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);

        // Getting LocalTine from OffsetTime
        LocalTime result = offsetTime.toLocalTime();
        System.out.println(result);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出

15:30+03:00
15:30
Run Code Online (Sandbox Code Playgroud)

在线演示

或者:

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

        // Getting LocalTine from OffsetTime
        LocalTime result = offsetTime.toLocalTime();
        System.out.println(result);
    }
}
Run Code Online (Sandbox Code Playgroud)

在线演示

从Trail: Date Time中了解有关现代日期时间 API 的更多信息。