どうしたい?
年/月/日は国毎に表示する順序が異なる。 2018年12月17日を端末の設定言語ごとに下記のように表示したい。
言語 | 表示 |
---|---|
英語(アメリカ) | 12/17/18 |
英語(イギリス) | 17/12/2018 |
日本 | 2018/12/17 |
どうやる?
JSR310 を利用すると簡単に実装できます。 Android では AndroidThreeTen を。
LocalDateTime.now().format(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT))
FormatStyle.SHORT
はフォーマットのスタイルを定義してあります。 FULL
, LONG
, MEDIUM
, SHORT
などがあり、お好みのフォーマットを当ててください。
2017年12月17日をそれぞれのフォーマットに当てると下記のような結果になります。
FormatStyle.SHORT
言語 | 表示 |
---|---|
English(United Kingdom) | 17/12/2018 |
English(United States) | 12/17/18 |
Japanese | 2018/12/17 |
FormatStyle.MEDIUM
言語 | 表示 |
---|---|
English(United Kingdom) | 17 Dec 2018 |
English(United States) | Dec 17, 2018 |
Japanese | 2018/12/17 |
FormatStyle.LONG
言語 | 表示 |
---|---|
English(United Kingdom) | 17 December 2018 |
English(United States) | December 17, 2018 |
Japanese | 2018年12月17日 |
FormatStyle.FULL
言語 | 表示 |
---|---|
English(United Kingdom) | Monday, 17 December 2018 |
English(United States) | Monday, December 17, 2018 |
Japanese | 2018年12月17日月曜日 |
上の例では日付だけをフォーマットしていますが、日付日時を同時に行いたい場合は ofLocalizedDateTime(FormatStyle)
を利用することができます。
おまけ
上で適用したフォーマットから milliseconds へ変更する。つまり逆のこと。結構面倒で3ステップくらいあります。
- text -> LocalDate
- LocalDate -> ZonedDateTime
- ZonedDateTime -> milliseconds
// 注意: FormatStyle は^で変更したものと同じものを使用してください。
val localDate = LocalDate.parse(formattedText, DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT))
val zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault())
val milliseconds = zonedDateTime.toInstant().toEpochMilli()
まとめると下記です。
// まとめ
LocalDate.parse(formattedText, formatter)
.atStartOfDay(ZoneId.systemDefault())
.toInstant()
.toEpochMilli()
その他
簡単な AndroidThreeTen の使い方集です。