APIにパラメーターとして送るときなど、Unixtimeに変換したい場合があると思います。
今回は文字列の日付をUnixtimeに変換する方法を紹介します。
手順
画面表示に使うなどした、日付の文字列があるとします。
val formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日")
val str = LocalDate.now().format(formatter) //"2019年9月1日"
binding.textView.text = str // 画面に表示する
1. String
→ LocalDate
の変換
2019年9月1日
から2019-09-01
に変換します。
val localDate = LocalDate.parse(str, formatter) // 2019-09-01
2. LocalDate
→ ZonedDateTime
の変換
2019-09-01
から2019-09-01T00:00+09:00
に変換します。
val zonedDateTime = localDate.atStartOfDay(ZoneOffset.ofHours(+9)) // 2019-09-01T00:00+09:00
-
ZonedDateTime
はタイムゾーンごとの時間付きの日付を扱うクラス - JST(日本標準時)にしたいので、引数に
ZoneOffset.ofHours(+9)
を渡す - UTC(協定世界時)にしたい場合は、引数に
ZoneOffset.UTC
を渡す
3. ZonedDateTime
→ Unixtime
の変換
2019-09-01T00:00+09:00
から1567263600
に変換します。
val unixTime = zonedDateTime.toEpochSecond() // 1567263600
- 上記
unixTime
の型はLong
なので、必要に応じてInt
に変換する - 無事Unixtimeを取得できました🎉
まとめ
文字列の日付をUnixtimeに変換するには
String
→ LocalDate
→ ZonedDateTime
→ Unixtime(Long)
と何度も変換をおこなう必要があり、ちょっと面倒でした。(もっと簡単なやり方があれば教えて下さい)
最後にコードをまとめておきます。
private fun getUnixTime(): Int {
val formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日")
val str = LocalDate.now().format(formatter)
val localDate = LocalDate.parse(str, formatter)
val zonedDateTime = localDate.atStartOfDay(ZoneOffset.ofHours(+9))
return zonedDateTime.toEpochSecond().toInt()
}
こんな感じで拡張関数にしておくと便利です。
fun String.toUnixTime(formatter: DateTimeFormatter): Int {
val localDate = LocalDate.parse(this, formatter)
val zonedDateTime = localDate.atStartOfDay(ZoneOffset.ofHours(+9))
return zonedDateTime.toEpochSecond().toInt()
}