Skip to content

Instantly share code, notes, and snippets.

@oeddyo
Created March 25, 2015 23:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oeddyo/40078df432c65189486f to your computer and use it in GitHub Desktop.
Save oeddyo/40078df432c65189486f to your computer and use it in GitHub Desktop.
case class RichDate(val timestamp: Long) extends AnyVal with Ordered[RichDate] {
//case class RichDate(val timestamp: Long) extends Ordered[RichDate] {
// these are mutable, don't keep them around
def value: Date = new java.util.Date(timestamp)
def +(interval: Duration) = interval.addTo(this)
def -(interval: Duration) = interval.subtractFrom(this)
//Inverse of the above, d2 + (d1 - d2) == d1
def -(that: RichDate) = AbsoluteDuration.fromMillisecs(timestamp - that.timestamp)
override def compare(that: RichDate): Int =
Ordering[Long].compare(timestamp, that.timestamp)
/*
//True of the other is a RichDate with equal value, or a Date equal to value
override def equals(that: Any) =
that match {
case d: Date => d.getTime == timestamp
case RichDate(ts) => ts == timestamp
case _ => false
}
*/
/**
* Use String.format to format the date, as opposed to toString with uses SimpleDateFormat
*/
def format(pattern: String)(implicit tz: TimeZone): String = String.format(pattern, toCalendar(tz))
/**
* Make sure the hashCode is the same as Date for the (questionable) choice
* to make them equal. this is the same as what java does (and only sane thing):
* http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Date.java#989
*/
/*
override def hashCode =
(timestamp.toInt) ^ ((timestamp >> 32).toInt)
*/
def toCalendar(implicit tz: TimeZone) = {
val cal = Calendar.getInstance(tz)
cal.setTime(value)
cal
}
override def toString = value.toString
/**
* Use SimpleDateFormat to print the string
*/
def toString(fmt: String)(implicit tz: TimeZone): String = {
val cal = toCalendar(tz)
val sdfmt = new SimpleDateFormat(fmt)
sdfmt.setCalendar(cal)
sdfmt.format(cal.getTime)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment