LoginSignup
0
2

More than 3 years have passed since last update.

ScalaでUnix timestampからLocalDatetimeを取得する

Posted at

特にScalaに限った話ではなく、Javaでも同様です。自分用のメモです。

Unixのtimestampが与えられたとき、それをjava.time.LocalDateTimeに変換するには、

main.scala
import java.time._

def fromUnixMilliSecond(ts: Long): LocalDateTime =
  LocalDateTime.ofInstant(Instant.ofEpochMilli(ts), ZoneOffset.UTC)

という感じに書けます。

ミリ秒ではなく、秒の場合は

main.scala
import java.time._

def fromUnixSecond(ts: Long): LocalDateTime =
  LocalDateTime.ofInstant(Instant.ofEpochSecond(ts), ZoneOffset.UTC)

と書けます。

Instantは元のtimestampの単位が、秒かミリ秒かによって呼ぶメソッドが異なるので、分かりやすい感じがします。

参考

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