0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

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

Last updated at Posted at 2021-03-11

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便利〜。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?