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

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

More than 1 year has passed since last update.

概要

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
Why do not you register as a user and use Qiita more conveniently?
  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
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