Wednesday, March 11, 2020

Tips: Dealing with joda time LocalDate comparison in scala using implicit class

If you are coming from C#, working with DateTime is pretty straight forward. You can compare equal, greater than, less than, or getting the day difference from two dates without any hassle. But if you are in Scala, using joda time, it's not easy to get it right at the right for the first time. the LocalData has several functions can be used to compare the date-time. They are isAfter, isEqual, isBefore, and daysBeetween to get the diff of the day.

Here is my favorite approach to deal with joda time LocalDate comparison. First, we need to create an implicit class. In C#, this is comparable to the Extension Method. We can add or extend the functionality of a class without modifying the class implementation. In this case, we will extend LocalData as below:

----------------------
import org.joda.time.{Days, LocalDate}
object LocalDateExtension {   class LocalDateExtension(a: LocalDate) {     def dayDiff(b: LocalDate): Int = {       Days.daysBetween(a, b).getDays.abs     }
    def >(b: LocalDate): Boolean = {       a.isAfter(b)     }
    def >=(b: LocalDate): Boolean = {       a.isAfter(b) || a.isEqual(b)     }
    def <(b: LocalDate): Boolean = {       a.isBefore(b)     }
    def <=(b: LocalDate): Boolean = {       a.isBefore(b) || a.isEqual(b)     }   }
  implicit def extendLocalDate(a: LocalDate) = new LocalDateExtension(a) }
------------------------

What we are doing here? In scala, we are allowed to name a method using any character such as equal, greater than, or less than signs. This way, we can use the same syntax we use in C# to compare dates. For example as below:

----------------------
import org.joda.time.{Days, LocalDate}
val a = LocalDate("2010-04-28") val b = LocalDate("2010-04-29")
print(a > b) // false print(a >= b) // false print(a < b) // true print(a <= b) // true
------------------------


Finally, C# 9 record, the equivalent of Scala's case class

While C# is a wonderful programming language, there is something that I would like to see to make our life programmer easier. If you are fam...