以下の内容はhttps://dk521123.hatenablog.com/entry/2023/03/08/000000より取得しました。


【Scala】Scala ~ 基本編 / 日付・日時 ~

■ はじめに

今回は、Scala の 日付/日時の扱いについて触れる。
徐々に書き溜めていく、、、

目次

【1】java.time
 0)使用上の注意
 1)日付/日時フォーマット
 2)年齢の計算
【2】java.util.Date
 0)使用上の注意
 1)日付/日時フォーマット

【1】java.time

基本的に、
Java8以降の 標準的なDate and Time APIである
java.time(JSR-310)を使えばよさそう。
ちゃんと、Serializableだし、Immutableでスレッドセーフだし。。。

https://docs.oracle.com/javase/jp/8/docs/api/java/time/package-summary.html

java.time.format.DateTimeFormatterはSerializableじゃない
(日付の扱うUtilクラスとか作ってラップしたほうがいいかも)

https://docs.oracle.com/javase/jp/8/docs/api/java/time/format/DateTimeFormatter.html

* 詳細は、以下のサイトが参考になりそう

https://qiita.com/suema0331/items/35da67426ffea0fb4435
https://atmarkit.itmedia.co.jp/ait/articles/1412/16/news041.html

0)使用上の注意

* 午前(AM)・午後(PM)の区別があるので、
 withLocale(Locale.ENGLISH)を指定しておく方がいい
 => 日本語のOSだと「午前」「午後」で表示される

1)日付/日時フォーマット

例1:Hello world

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

object Hello {
  def main(args: Array[String]): Unit = {
    val formatter = DateTimeFormatter.ofPattern("YYYY/MM/dd")
    val targetDate = LocalDateTime.of(2012, 1, 23, 12, 34, 56);
    val formatted = targetDate.format(formatter);
    println(formatted)
  }
}

例2:TryでParse失敗時に備える

import java.time.{LocalDateTime, ZoneOffset}
import java.time.format.DateTimeFormatter
import java.util.Locale
import scala.util.{Success, Try}

object Hello {
  def main(args: Array[String]): Unit = {
    val values = List(
      "2020/12/12 11:21:11",
      "12/1/2021 1:11:12 AM",
      "2020-12-12 05:06:03"
    )
    val inputPattern =
      DateTimeFormatter.ofPattern("M/d/yyyy h:mm:ss a").withLocale(Locale.ENGLISH)
    val outputPattern =
      DateTimeFormatter.ofPattern("yyyy/MM/dd").withLocale(Locale.ENGLISH)

    values.foreach(value => {
      val result = Try(LocalDateTime.parse(value, inputPattern)) match {
          case Success(parsed) =>
            parsed.atOffset(ZoneOffset.UTC).format(outputPattern)
          case _ =>
            s"Failed - $value"
        }
      println(s"Result - $result (value=$value)")
    })
  }
}

// 出力結果例
// Result - Failed - 2020/12/12 11:21:11 (value=2020/12/12 11:21:11)
// Result - 2021/12/01 (value=12/1/2021 1:11:12 AM)
// Result - Failed - 2020-12-12 05:06:03 (value=2020-12-12 05:06:03)

2)年齢の計算

例1:Period

import java.time.{LocalDate, Period}

object Hello {
  def main(args: Array[String]): Unit = {
    val birthDay = LocalDate.of(1977, 10, 10)
    val period = Period.between(birthDay, LocalDate.now)
    // 46
    println(period.getYears)
  }
}

例2:ChronoUnit.YEARS.between
https://docs.oracle.com/javase/jp/8/docs/api/java/time/temporal/ChronoUnit.html

import java.time.LocalDate
import java.time.temporal.ChronoUnit

object Hello {
  def main(args: Array[String]): Unit = {
    val targetDate = "2005-07-09"
    val dateTime = LocalDate.parse(targetDate)
    // 2024-07-10
    val now = LocalDate.now()

    // !!注目!!
    val age = ChronoUnit.YEARS.between(dateTime, now)
    // 19
    println(age)
  }
}

【2】java.util.Date

0)使用上の注意

* ただ、ほとんどが非推奨だから使用は控えたほうがいいかも、、、

https://www.lac.co.jp/lacwatch/people/20220720_003047.html

1)日付/日時フォーマット

import java.util.Date

val date1 = "%tY%<tm%<td" format new Date
// e.g. 20230316
println(date1)

val date2 = "%tY/%<tm/%<td" format new Date
// e.g. 2023/03/16
println(date2)

val date3 = "%tF" format new Date
// e.g. 2023-03-16
println(date3)

val datetime1 = "%tY/%<tm/%<td %<tH:%<tM:%<tS" format new Date
// e.g. 2023/03/16 21:35:35
println(date2)

参考文献

http://blog.mwsoft.jp/article/45391549.html
https://www.qoosky.io/techs/8471c8d3c0

関連記事

Scala ~ 環境構築編 ~
https://dk521123.hatenablog.com/entry/2023/03/10/193805
Scala ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2023/03/12/184331
Scala ~ 基本編 / メソッド ~
https://dk521123.hatenablog.com/entry/2023/03/03/000000
Scala ~ 基本編 / クラス ~
https://dk521123.hatenablog.com/entry/2023/03/14/000857
Scala ~ 基本編 / コレクション ~
https://dk521123.hatenablog.com/entry/2023/03/13/000345
Scala ~ 基本編 / 例外処理 ~
https://dk521123.hatenablog.com/entry/2023/10/05/000135
Scala ~ Joda-Time ~
https://dk521123.hatenablog.com/entry/2024/07/10/001348
ScalaYAML
https://dk521123.hatenablog.com/entry/2023/03/16/012034




以上の内容はhttps://dk521123.hatenablog.com/entry/2023/03/08/000000より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14