Skip to content

Instantly share code, notes, and snippets.

@frgomes
Last active January 23, 2022 23:15
Show Gist options
  • Save frgomes/c6bf34eeb5ae1769b072 to your computer and use it in GitHub Desktop.
Save frgomes/c6bf34eeb5ae1769b072 to your computer and use it in GitHub Desktop.
Scala - Converts Any to Double, to LocalDate and Date
// this flavour is pure magic...
def toDouble: (Any) => Double = { case i: Int => i case f: Float => f case d: Double => d }
// whilst this flavour is longer but you are in full control...
object any2Double extends Function[Any,Double] {
def apply(any: Any): Double =
any match { case i: Int => i case f: Float => f case d: Double => d }
}
// like when you can invoke any2Double from another similar conversion...
import java.time.{LocalDate, ZoneId}
object any2LocalDateExcel extends Function[Any,LocalDate] {
def apply(any: Any): LocalDate =
LocalDate.ofEpochDay(0).plusDays(any2Double(any).intValue-25569)
}
// and again...
import java.util.Date
object any2DateExcel extends Function[Any,Date] {
def apply(any: Any): Date =
Date.from(any2LocalDateExcel(any).atStartOfDay(ZoneId.systemDefault()).toInstant())
}
@umbertogriffo
Copy link

Very Usefull!

@beaulishi
Copy link

Very Usefull! so cool thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment