LoginSignup
1
0

More than 5 years have passed since last update.

Scalaで日付を丸めたいときのサンプルコード

Posted at

概要

Scalaで日付を扱う際に、丸めを行いたいときのサンプルコードです。丸目とは例えば日付単位であれば、12月1日の1時1分1秒を、12月1日の0時0分0秒にしたいときのことを指します。

方法

JavaのライブラリであるJoda-Timeを使用して丸目をおこないます。Javaでの対応は@rubytomato@githubさんのJoda-Timeを使った日付処理まとめのroundの項にありますので、Scalaでも同様の方法で実装します。
ScalaではJoda-Timeをラッパーした「nscala-time」というライブラリがあるので、nscala-timeを使用します。(nscala-timeの詳細は@yhidaiさんのnscala-timeで学ぶImplicit Conversionを参照)

サンプルコード

NscalaTest.scala
import com.github.nscala_time.time.Imports._

object NscalaTest{
  def main() = {
    // (1)現在時刻
    println(DateTime.now)
    // (2)minute以降を切り捨て
    println(DateTime.now.hour.roundFloor)
    // (3)hour以降を切り捨て
    println(DateTime.now.day.roundFloor)
  }
}

現在日時が2018/12/1 01:05:41の場合の、(1)~(3)の結果は以下の通りとなります。

// (1)
2018-12-01T01:05:41.788+09:00
// (2)
2018-12-01T01:00:00.000+09:00
// (3)
2018-12-01T00:00:00.000+09:00
1
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
1
0