LoginSignup
8
7

More than 3 years have passed since last update.

【Kotlin】日付文字列をUnixtimeに変換する方法

Last updated at Posted at 2019-08-31

APIにパラメーターとして送るときなど、Unixtimeに変換したい場合があると思います。
今回は文字列の日付をUnixtimeに変換する方法を紹介します。

手順

画面表示に使うなどした、日付の文字列があるとします。

val formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日")
val str = LocalDate.now().format(formatter) //"2019年9月1日"

binding.textView.text = str // 画面に表示する

1. StringLocalDateの変換

2019年9月1日から2019-09-01に変換します。

val localDate = LocalDate.parse(str, formatter) // 2019-09-01

2. LocalDateZonedDateTimeの変換

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. ZonedDateTimeUnixtimeの変換

2019-09-01T00:00+09:00から1567263600に変換します。

val unixTime = zonedDateTime.toEpochSecond() // 1567263600
  • 上記unixTimeの型はLongなので、必要に応じてIntに変換する
  • 無事Unixtimeを取得できました🎉

まとめ

文字列の日付をUnixtimeに変換するには
StringLocalDateZonedDateTimeUnixtime(Long)
と何度も変換をおこなう必要があり、ちょっと面倒でした。(もっと簡単なやり方があれば教えて下さい:pray:

最後にコードをまとめておきます。

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

参考

【LocalDate/LocalDateTime】Java8以降で秒単位またはミリ秒単位のUnixTimeを取得する方法まとめ【EpochSecond/EpochMilli】 | Blogenist – ブロゲニスト

8
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7