Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.cubicle6.time
- import com.cubicle6.time.Instant._
- /**
- * Duration class which stores durations as milliseconds and
- * facilitates operations that produce time instants. Simple
- * addition and subtraction between Duration instances is also
- * provided.
- */
- case class Duration(val milliseconds: Double) {
- // Mathematic operations
- def + (d: Duration): Duration =
- new Duration(this.milliseconds + d.milliseconds)
- def - (d: Duration): Duration =
- new Duration(this.milliseconds - d.milliseconds)
- def + (i: Instant): Instant =
- i + this
- def - (i: Instant): Instant =
- i - this
- // Time relation operations
- def and(d: Duration): Duration =
- this + d
- def from(i: Instant): Instant =
- new Instant(i.milliseconds + milliseconds)
- def ago(): Instant =
- before(now)
- def before(i: Instant): Instant =
- new Instant(i.milliseconds - milliseconds)
- // Unit conversions
- def toSeconds: Double =
- this.milliseconds / 1000
- def toMinutes: Double =
- this.milliseconds / (1000 * 60)
- def toHours: Double =
- this.milliseconds / (1000 * 60 * 60)
- def toDays: Double =
- this.milliseconds / (1000 * 60 * 60 * 24)
- // Boring operations
- override def toString(): String =
- "Duration: " + this.milliseconds + " ms"
- override def hashCode: Int = super.hashCode + milliseconds.hashCode
- }
- /**
- * Duration Value class used for implementing the time DSL
- */
- class DurationValue(val value: Double) {
- // Single units
- def millisecond: Duration =
- new Duration(value)
- def second: Duration =
- new Duration(value * 1000)
- def minute: Duration =
- new Duration(value * 1000 * 60)
- def hour: Duration =
- new Duration(value * 1000 * 60 * 60)
- def day: Duration =
- new Duration(value * 1000 * 60 * 60 * 24)
- // Plural units
- def milliseconds(): Duration =
- new Duration(value)
- def seconds(): Duration =
- new Duration(value * 1000)
- def minutes(): Duration =
- new Duration(value * 1000 * 60)
- def hours(): Duration =
- new Duration(value * 1000 * 60 * 60)
- def days(): Duration =
- new Duration(value * 1000 * 60 * 60 * 24)
- }
- /**
- * Duration Singleton Object. Contains implicits.
- */
- object Duration {
- implicit def double2durationValue(double: Double): DurationValue =
- new DurationValue(double)
- implicit def float2durationValue(float: Float): DurationValue =
- new DurationValue(float.doubleValue)
- implicit def integer2durationValue(integer: Int): DurationValue =
- new DurationValue(integer.doubleValue())
- implicit def long2durationValue(long: Long): DurationValue =
- new DurationValue(long.doubleValue())
- implicit def duration2long(duration: Duration): Long =
- duration.milliseconds.longValue
- }
Add Comment
Please, Sign In to add comment