Skip to content

Instantly share code, notes, and snippets.

@salzig
Created April 25, 2012 08:48
Show Gist options
  • Save salzig/2488278 to your computer and use it in GitHub Desktop.
Save salzig/2488278 to your computer and use it in GitHub Desktop.
Scala Time
package time
object App {
def main(args:Array[String]) {
import TimeImplicit._
println(10 ns)
println(20 µs)
println(30 ms)
println(40 s)
println(50 m)
println(-1 s)
println(10.s + 20.ms)
println(20.ms + 10.s)
println(10.s - 20.ms)
println(20.ms - 10.s)
println(20.ms - 10.s)
println(20.ms + 10.s)
println(1.m - 200.s)
// println(1.ns + 2.µs + 3.ms + 4.s + 5.m -1.m)
println(1.ns + 2.µs + 3.ms + 4.s + 5.m)
// 10.s.s
// 10.sec+10
}
}
object TimeUnit extends Enumeration {
type TimeUnit = Value
val noTime, nanosecond, microsecond, millisecond, second, minute = Value
}
import TimeUnit._
protected class Time(protected val value:Long, val scale:TimeUnit=second) {
def +(other:Time)={
if (scale > other.scale) {
Time(value*shift(other) + other.value, other.scale)
}
else {
Time(value + other.value*shift(other), scale)
}
}
def -(other:Time)={
if (scale > other.scale) {
Time(value*shift(other) - other.value, other.scale)
}
else {
Time(value - other.value*shift(other), scale)
}
}
private def shift(other:Time)=
if (scale > other.scale)
Time.scaleTable(scale) / Time.scaleTable(other.scale)
else
Time.scaleTable(other.scale) / Time.scaleTable(scale)
// def -(other:Time)
override def toString = "%d %s" format (value,scale)
}
object Time {
val scaleTable = Map(noTime -> 1l, nanosecond -> 1l, microsecond -> 1000l, millisecond -> 1000000l, second -> 1000000000l, minute -> 60*1000000000l)
def apply(v:Long, s:TimeUnit) = if (v >= 0) new Time(v,s) else NaT
object NaT extends Time(0,noTime) {
override def toString="NaT"
}
}
class TimeFactory(val value:Long) {
def ns()= if (value >= 0) Time(value, nanosecond) else Time.NaT
def µs()= if (value >= 0) Time(value, microsecond) else Time.NaT
def ms()= if (value >= 0) Time(value, millisecond) else Time.NaT
def s()= if (value >= 0) Time(value, second) else Time.NaT
def m()= if (value >= 0) Time(value, minute) else Time.NaT
}
object TimeImplicit {
implicit def long2time(v:Long):TimeFactory = new TimeFactory(v)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment