■ はじめに
今回は、Scala の 日付/日時の扱いについて触れる。 徐々に書き溜めていく、、、
目次
【1】java.time 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
1)日付/日時フォーマット
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)年齢の計算
例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
Scala ~ YAML ~
https://dk521123.hatenablog.com/entry/2023/03/16/012034