如何将ZonedDateTime格式化为字符串? [英] How to format a ZonedDateTime to a String?

查看:1042
本文介绍了如何将ZonedDateTime格式化为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

找到了如何更改时区:

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

推荐答案

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

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

这里有个例子

ZonedDateTime date = ZonedDateTime.now();

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

这篇关于如何将ZonedDateTime格式化为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆