Anneso
Anneso

Reputation: 613

How to compare 2 java.sql.Date in scala?

I have some date in format java.sql.Date and I want to compare them

import java.sql.Date
import org.apache.spark.sql.types.{DateType, IntegerType}
var a = Date.valueOf("2018-11-09")
var b = Date.valueOf("2019-11-09")

a: java.sql.Date = 2018-11-09
b: java.sql.Date = 2019-11-09

If I compare with an equal sign it work

a == b
res1: Boolean = false

But if I want to know which one is bigger than the other it return an error:

 a >= b
<console>:37: error: value > is not a member of java.sql.Date

I would expect it to return false.

How can I compare a and b.?

Upvotes: 0

Views: 1815

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170735

If you want to use the comparison operators such as a >= b instead of compareTo, you can: just add

import scala.math.Ordering.Implicits._

for Comparable types. java.sql.Date is actually a bit unusual, because it's Comparable with java.util.Date and not java.sql.Date. So for this type you need type ascription:

(a: java.util.Date) >= b

Upvotes: 3

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521194

You may use java.sql.Date#compareTo:

var a = Date.valueOf("2018-11-09")
var b = Date.valueOf("2019-11-09")

if (b.compareTo(a) > 0) {
    println("Date b is later than date a.");
}

Upvotes: 4

Related Questions