简体   繁体   English

ZonedDateTime 本地化格式

[英]ZonedDateTime localized format

I want to display ZonedDateTime in format like我想以如下格式显示 ZonedDateTime

11.10.2022 13:30 (GMT+2) / 11.10.2022 01:30 PM (GMT+2) 11.10.2022 13:30 (GMT+2) / 11.10.2022 01:30 PM (GMT+2)

depending on device settings.取决于设备设置。 So far I have done something similar using formatDateTime function from DateUtils class, but this function doesn't display到目前为止,我已经使用 DateUtils 类中的 formatDateTime 函数做了类似的事情,但是这个函数不显示

(GMT+2) (格林威治标准时间+2)

It takes time in milliseconds as a argument.它需要以毫秒为单位的时间作为参数。 How can I do this with ZonedDateTime?我如何使用 ZonedDateTime 做到这一点?

Use DateTimeFormatter helper from java.time.format to format ZonedDateTime , for example:使用java.time.format中的DateTimeFormatter助手来格式化ZonedDateTime ,例如:

val time = ZonedDateTime.now()
val formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm (O)")
formatter.format(time) // will return time in format 11.10.2022 13:30 (GMT+2)

See which symbols you can use to construct the pattern in the official docs .查看官方文档中可以使用哪些符号来构建模式。

To implement your particular case, you can also use DateTimeFormatterBuilder :要实现您的特定情况,您还可以使用DateTimeFormatterBuilder

val time = ZonedDateTime.now()
val formatter = DateTimeFormatterBuilder()
    .appendPattern("dd.MM.yyyy ")
    .appendLocalized(null, FormatStyle.SHORT)
    .appendPattern(" (O)")
    .toFormatter()
formatter.format(time) // will return time depending on Locale

The last line of the code will return time in the desired format:代码的最后一行将以所需格式返回时间:

11.10.2022 13:30 (GMT+2) / 11.10.2022 01:30 PM (GMT+2) 11.10.2022 13:30 (GMT+2) / 11.10.2022 01:30 PM (GMT+2)

Depending on device Locale:取决于设备区域设置:

Locale.FRANCE / Locale.US Locale.FRANCE / Locale.US

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM