java - TimeFormat 始终来自特定时区
问题描述
我在创建应用程序时遇到日期格式问题,我无法从当前语言环境格式化时间,但总是从特定语言环境 UTC+1 或特定状态格式化时间,但我不知道如何。
SimpleDateFormat("d.M.yyyy HH:mm", Locale.getDefault()).format(Date(date))
我需要设置区域设置或时区,例如常量,不依赖于物理位置或电话设置。
我的数据始终为 UTC-0,但我需要将其转换为 UTC+1(或其他)并显示给用户。
谢谢你的帮助
对于时间同步,我使用 TrueTime 库
解决方案
这是一个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.time
Android 26 以下 API 级别几乎所有功能的反向移植。
我认为,如今,使用java.time
它或向后移植它是解决像你这样的任务的最简单、最直接的方法。
推荐阅读
- ios - UICollectionview 在部分之间有不需要的空间
- sqliteexception - 某些设备中的 android.database.sqlite.SQLiteException
- r - 如何通过使用plot()函数R通过分类列的值增加颜色的阴影来为绘图着色
- javascript - 如何在发送到服务器之前将 mimetype (video/webm) 和编解码器 (vp9) 添加到 blob 对象
- php - 如何使用 laravel 注册验证器返回错误
- php - 在php中搜索带有条件的数组
- angular - 为什么 Chrome 在使用 Angular Service-Worker 时会显示重复的 HTTP 请求?
- elasticsearch - Elasticsearch - cologne 和 koelnerphonetik 编码器的区别
- java - 在 API Retrofit PUT 调用中将自定义对象数组作为参数传递
- angular - ngmodule 不是子类型 ngmoduletype