簡體   English   中英

ZonedDateTime 本地化格式

[英]ZonedDateTime localized format

我想以如下格式顯示 ZonedDateTime

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

取決於設備設置。 到目前為止,我已經使用 DateUtils 類中的 formatDateTime 函數做了類似的事情,但是這個函數不顯示

(格林威治標准時間+2)

它需要以毫秒為單位的時間作為參數。 我如何使用 ZonedDateTime 做到這一點?

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

查看官方文檔中可以使用哪些符號來構建模式。

要實現您的特定情況,您還可以使用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

代碼的最后一行將以所需格式返回時間:

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

取決於設備區域設置:

Locale.FRANCE / Locale.US

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM