How to format a ZonedDateTime to a String?

社会主义新天地 提交于 2020-06-06 04:44:30

问题


I want to convert a ZonedDateTime to a String in 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().

How can I format a ZonedDateTime to 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:

Found how to change the timezones:

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

回答1:


You can use 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));



回答2:


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

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))


来源:https://stackoverflow.com/questions/42425393/how-to-format-a-zoneddatetime-to-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!