Android - 用时区转换当前日期和时间

Android - Converting current date and time with timezone

如何将当前时间转换为 2018-09-21T01:56:57.926986+00:00 on android?我正在使用 DateFormat 但我不知道如何在其上添加时区。这是我在获取当前日期和时间时使用的代码

DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
                                    Date date = new Date();
                                    String curDate = dateFormat.format(date);

提前致谢

tl;博士

使用java.timeclasses.

OffsetDateTime            // Represent a moment as a date, a time-of-day, and an offset-from-UTC (a number of hours, minutes, seconds) with a resolution as fine as nanoseconds.
.now(                     // Capture the current moment. 
    ZoneOffset.UTC.       // Specify your desired offset-from-UTC. Here we use an offset of zero, UTC itself, predefined as a constant.
)                         // Returns a `OffsetDateTime` object.
.format(                  // Generate text in a `String` object representing the date-time value of this `OffsetDateTime` object.
    DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ss.SSSSSSxxxxx" , Locale.US )
)                         // Returns a `String` object.

2018-09-27T05:39:41.023987+00:00

或者,使用 Z 作为 UTC。

Instant.now().toString()

2018-09-27T05:39:41.023987Z

java.time

现代方法使用 java.time 取代了可怕的旧日期时间 classes.

具体来说:

  • 使用 InstantOffsetDateTime 而不是 java.util.Date
  • 使用 DateTimeFormatter 而不是 `SimpleDateFormat。

获取 UTC 的当前时间。我们在生成文本时使用 OffsetDateTime class 而不是 Instant 以获得更灵活的格式。

ZoneOffset offset = ZoneOffset.UTC;
OffsetDateTime odt = OffsetDateTime.now( offset );

定义格式模式以匹配您想要的输出。请注意,内置格式模式使用 Z 作为 +00:00 的标准 shorthand。 Z 表示 UTC,发音为“Zulu”。这种祖鲁时间格式很常见。我建议使用 Z 这样的格式。但是您明确要求零偏移量的长版本,因此我们必须使用自定义 DateTimeFormatter 对象。

DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ss.SSSSSSxxxxx" , Locale.US );
String output = odt.format( f );

2018-09-27T05:39:41.023987+00:00

仅供参考,此处讨论的格式符合 ISO 8601 标准。


关于java.time

java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

要了解更多信息,请参阅 Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310

您可以直接与数据库交换 java.time 对象。使用 JDBC driver compliant with JDBC 4.2 或更高版本。不需要字符串,不需要 java.sql.* classes.

从哪里获得java.time classes?