Java 如何将 ZonedDateTime 格式化为字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42425393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:08:51  来源:igfitidea点击:

How to format a ZonedDateTime to a String?

javastringjava-timezoneddatetime

提问by mFeinstein

I want to convert a ZonedDateTimeto a Stringin the format of ("dd/MM/yyyy - hh:mm"). I know this is possible in Joda-Time other types, just using their toString("dd/MM/yyyy - hh:mm")....But this doesn't work with ZonedDateTime.toString().

我想将转换ZonedDateTimeString以格式("dd/MM/yyyy - hh:mm")。我知道这在 Joda-Time 其他类型中是可能的,只需使用它们的toString("dd/MM/yyyy - hh:mm")....但这不适用于ZonedDateTime.toString().

How can I format a ZonedDateTimeto a String?

如何ZonedDateTime将 a格式化为 a String



EDIT:

编辑:

I tried to print the time in another timezone and the result appears to be the same always:

我试图在另一个时区打印时间,结果似乎总是一样的:

ZonedDateTime date = ZonedDateTime.now();
ZoneId la = ZoneId.of("America/Los_Angeles");
ZonedDateTime date2 = date.of(date.toLocalDateTime(), la);

// 24/02/2017 - 04:53
System.out.println(DateTimeFormatter.ofPattern("dd/MM/yyyy - hh:mm").format(date));
// same result as the previous one
// 24/02/2017 - 04:53
System.out.println(DateTimeFormatter.ofPattern("dd/MM/yyyy - hh:mm").format(date2));

And I am not in the same timezone as Los Angeles.

而且我和洛杉矶不在同一个时区。



EDIT 2:

编辑2:

Found how to change the timezones:

找到了如何更改时区:

// Change this:
ZonedDateTime date2 = date.of(date.toLocalDateTime(), la); // incorrect!
// To this:
ZonedDateTime date2 = date.withZoneSameInstant(la);

采纳答案by reos

You can use java.time.format.DateTimeFormatter. https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

您可以使用 java.time.format.DateTimeFormatter。 https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

Here there is an example

这里有一个例子

ZonedDateTime date = ZonedDateTime.now();

System.out.println(DateTimeFormatter.ofPattern("dd/MM/yyyy - hh:mm").format(date));

回答by Tony Fraser

Many thanks for above. Here it is in scala where localDateTime.now always Zulu/UTC time.

非常感谢以上。这是在 Scala 中的 localDateTime.now 总是祖鲁语/UTC 时间。

import java.time.format.DateTimeFormatter
import java.time.LocalDateTime
import java.time.ZoneId

val ny = ZoneId.of("America/New_York")
val utc = ZoneId.of("UTC")
val dateTime = LocalDateTime.now.atZone(utc)

val nyTime = DateTimeFormatter.
      ofPattern("yyyy-MMM-dd HH:mm z").
      format(dateTime.withZoneSameInstant(ny))