🕘

【Android】ThreeTenABP の LocalDateTime を UNIX タイムスタンプに変換する

2021/03/09に公開

ThreeTenABPLocalDateTimeをUNIXタイムスタンプに変換する方法です。

今回はJST(日本標準時)に変換したいと思います。

事前準備として「ライブラリの追加・ThreeTenABPの初期化・現在日時の取得」を行います。

// app/build.gradle
implementation 'com.jakewharton.threetenabp:threetenabp:1.3.0'

// MainActivity.kt
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
	
	// 初期化
        AndroidThreeTen.init(this)
	// 現在のLocalDateTimeを取得
        val nowDateTime = LocalDateTime.now()
}

ZoneOffset#ofHours

ZoneOffset#ofHoursは、UTCからの時差を指定します。
UTCとJSTの時差は「9時間」で、UTCが「09:00」のときJSTは「18:00」となるので、9時間加算します。

nowDateTime.toEpochSecond(ZoneOffset.ofHours(9))
nowDateTime.toEpochSecond(ZoneOffset.ofHours(+9))

ちなみにOffsetとは「ある基準点からの距離を表した値」という意味で、ここでは「基準点->UTC」で「距離->時差」ということですね。

ZoneId#of

ZoneId#ofは、タイムゾーンIDを文字列で渡して、返されたZoneIdからタイムスタンプを取得します。

以下のように、複数パターンの文字列を渡すことが出来ます。

nowDateTime.atZone(ZoneId.of("UTC+09:00")).toEpochSecond()
nowDateTime.atZone(ZoneId.of("UTC+09")).toEpochSecond()
nowDateTime.atZone(ZoneId.of("UTC+9")).toEpochSecond()
nowDateTime.atZone(ZoneId.of("UT+09:00")).toEpochSecond()

まとめ

ThreeTenABP便利〜。

Discussion

ログインするとコメントできます