首页 > 解决方案 > TimeFormat 始终来自特定时区

问题描述

我在创建应用程序时遇到日期格式问题,我无法从当前语言环境格式化时间,但总是从特定语言环境 UTC+1 或特定状态格式化时间,但我不知道如何。

SimpleDateFormat("d.M.yyyy  HH:mm", Locale.getDefault()).format(Date(date))

我需要设置区域设置或时区,例如常量,不依赖于物理位置或电话设置。

我的数据始终为 UTC-0,但我需要将其转换为 UTC+1(或其他)并显示给用户。

谢谢你的帮助

对于时间同步,我使用 TrueTime 库

标签: javaandroiddatetimekotlinutc

解决方案


这是一个java.time使用ZonedDateTime从某个时刻创建的示例,即Instant在提到的包中的一个:

public static void main(String[] args) {
    // get a representation of a moment in time (not a specific date or time)
    Instant now = Instant.now();
    // then use that in order to represent it in a specific zone using an offset of -1 hour
    ZonedDateTime utcZdt = ZonedDateTime.ofInstant(now, ZoneOffset.ofHours(-1));
    // and use it again in order to have another one defined by a specific time zone
    ZonedDateTime laZdt = ZonedDateTime.ofInstant(now, ZoneId.of("America/Los_Angeles"));

    // and print the representation as String
    System.out.println(utcZdt.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
    System.out.println(laZdt.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
}

输出是

2020-02-18T14:31:21.714-01:00
2020-02-18T07:31:21.714-08:00[America/Los_Angeles]

您也可以使用OffsetDateTime相同的包。

关键是使用Instant, 派生自 epoch millis。这些毫秒值也是时间点,与区域或偏移量无关。

您正在编写一个 Android 应用程序,因此您可能必须使用ThreeTenABP,它是java.timeAndroid 26 以下 API 级别几乎所有功能的反向移植。

我认为,如今,使用java.time它或向后移植它是解决像你这样的任务的最简单、最直接的方法。


推荐阅读