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

问题描述 投票:0回答:3

作为输入,我得到一个类似 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()
}

我该怎么做?

android kotlin simpledateformat android-calendar timezone-offset
3个回答
5
投票

java.time

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

使用java.time API的解决方案

使用

LocalTime#parse
解析给定的时间字符串,然后使用
OffsetTime
 将其转换为 UTC 
LocalTime#atOffset
。最后一步是将此 UTC
OffsetTime
转换为
OffsetTime
偏移处的
+03:00
,您可以使用
OffsetTime#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);
    }
}

输出

15:30+03:00
15:30

在线演示

或者:

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

在线演示

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


3
投票

您可以为此使用

java.time
,如果您只想添加特定的小时数,则可以使用
LocalTime.parse(String)
LocalTime.plusHours(Long)
DateTimeFormatter.ofPattern("HH:mm")
。这是一个小例子:

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

输出很简单

15:30

尝试使用

"22:30"
,您将得到
"01:30"
作为输出。

请注意,如果您不应该只添加三个小时,而是考虑与 UTC 的偏移量可能会发生变化的实时时区,那么夏令时可能会导致问题。


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

此函数默认返回“GMT”,如果您想更改,请添加“GMT+5:30”

注意:根据您的要求更改格式

© www.soinside.com 2019 - 2024. All rights reserved.