java - 从设备获取当前时间毫秒并将其转换为具有不同时区的新日期

标签 java android date time timezone

<分区>

我现在面临的问题是 -

首先我创建了一个日期对象,它将给我当前日期和时间以及设备时区,即

Date date = new Date(); // Let say the time zone is India - GMT (+05:30)
The value of date is = "Mon Sep 24 13:54:06 GMT+05:30 2018"

不,我有一个日期格式化程序,我使用它转换了以下日期对象。

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss z");
sdf.setTimeZone(TimeZone.getTimeZone(loadPreferences(Utility.TIMEZONE_NAME)));
// Here the timezone is Hawaii (GMT-10:00)

现在根据新时区(即夏威夷)获取时间

String dateS = sdf.format(date); 
// This will give you the date with new timezone - "2018/09/23 22:24:06 GMT-10:00"

现在将此字符串日期转换为日期对象为 -

Date newDate = sdf.parse(dateS);

现在我得到的新日期与我经过的时区不符。

The value of newDate which i'm getting is = "Mon Sep 24 13:54:06 GMT+05:30 2018" 
//This is device timezone not the one i have set.

我已经在日期格式化程序中尝试了“Z”、“z”、“X”、“ZZ”、“ZZZZZ”,但仍然没有成功。

如果你们中的任何人对阅读本文有任何想法,请告诉我。

最佳答案

两条消息:

  • 你的期望是错误的。 Date 没有时区,它不可能有。因此,无论您如何编写代码,使用 DateSimpleDateFormat 都不可能获得您想要获得的内容。
  • DateSimpleDateFormatTimeZone 类早已过时且设计不佳。它们的现代替代品是 java.time,这是 2014 年推出的日期和时间 API。

分区日期时间

现代 ZonedDateTime 有一个时区,正如其名称所示:

    DateTimeFormatter formatter 
            = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss z", Locale.US);
    ZonedDateTime nowInHawaii = ZonedDateTime.now(ZoneId.of("Pacific/Honolulu"));
    String dateS = nowInHawaii.format(formatter);
    System.out.println(dateS);

这段代码的输出是:

2018/09/24 18:43:19 HST

如果您想要输出中的偏移量,请这样更改格式化程序:

    DateTimeFormatter formatter 
            = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss OOOO", Locale.US);

2018/09/24 18:45:53 GMT-10:00

问题:我可以在 Android 上使用 java.time 吗?

是的,java.time 在新旧 Android 设备上都能很好地工作。它只需要至少 Java 6

  • 在 Java 8 及更高版本以及新的 Android 设备(据我所知,从 API 级别 26 开始)中,现代 API 是内置的。
  • 在 Java 6 和 7 中获得 ThreeTen Backport,现代类的反向端口(ThreeTen for JSR 310,现代 API 首次被描述)。
  • 在(较旧的)Android 设备上,使用 ThreeTen Backport 的 Android 版本。它叫做 ThreeTenABP。确保从包 org.threeten.bp 和子包中导入日期和时间类。

链接

关于java - 从设备获取当前时间毫秒并将其转换为具有不同时区的新日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52475409/

相关文章:

android - 当我不使用 ContigouslyPagedList 时,ContigouslyPagedList onPageError

android - Geckoview (Firefox webview) Gradle 冲突问题( Lollipop 版本)

sql - MONTH AND YEAR 的 Rails Sql 查询

java - Kotlin 中的方法的返回类型应该是什么,该方法的值可以为 null 并且将从 Java 调用?

Javafx 子项溢出 FlowPane

java - 无法将数组传递到方法中

java - java中使用正则表达式获取子字符串

java - Android Studio - Java 库上的 MinSdkVersion

apache - Logstash 日期过滤器不使用 Apache 时间戳更新 @timestamp

php - 将日期值(字符串)转换为具有不同时区的时间戳