Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

特に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の単位が、秒かミリ秒かによって呼ぶメソッドが異なるので、分かりやすい感じがします。

参考

https://qiita.com/liguofeng29/items/c643c6f81afc62aac77d

https://docs.oracle.com/javase/jp/8/docs/api/java/time/LocalDateTime.html#ofInstant-java.time.Instant-java.time.ZoneId-

https://docs.oracle.com/javase/jp/8/docs/api/java/time/Instant.html#ofEpochMilli-long-

https://docs.oracle.com/javase/jp/8/docs/api/java/time/Instant.html#ofEpochSecond-long-

hiron2225
主に業務系アプリ開発をやっていて、得意言語はC#です。 その他、仕事でJava、VBA、Delphi(昔)、Python等を扱います。 あと、Powershellを少々。 よろしくお願いします。
nextbeat
「人口減少社会への価値貢献」をミッションとする創業5年のベンチャー企業です。子育て支援を中心としたライフイベント領域、インバウンド領域、地方創生領域を軸に全9事業を展開中!
https://www.nextbeat.co.jp/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした