How to round DateTime of Joda library to the nearest X minutes?

后端 未结 6 1555
[愿得一人]
[愿得一人] 2020-12-28 14:42

How to round DateTime of Joda library to the nearest X minutes ?
For example:

X = 10 minutes
Jun 27, 11:32 -> Jun 27, 11         


        
6条回答
  •  [愿得一人]
    2020-12-28 15:15

    Here's another approach that uses arithmetic on Unix time for completeness:

    (Implemented in Scala for clarity.)

    import org.joda.time.{DateTime, Duration}
    
    def roundDateTime(t: DateTime, d: Duration) = {
      t minus (t.getMillis - (t.getMillis.toDouble / d.getMillis).round * d.getMillis)
    }
    

    Example usage:

    roundDateTime(new DateTime("2013-06-27T11:32:00"), Duration.standardMinutes(10))
    // => 2013-06-27T11:30:00.000+02:00
    
    roundDateTime(new DateTime("2013-06-27T11:37:00"), Duration.standardMinutes(10))
    // => 2013-06-27T11:40:00.000+02:00
    

提交回复
热议问题