Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to compare string dates in scala without converting it into date type

I have two string dates

a = ‘2021-05-23
b = ‘2021-04-24"

I’m trying to define a function that compares two string dates and returns true if b is one month greater than a.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Can anyone help me?

Thanks

>Solution :

The question is a little bit unclear, like do you mean the difference would be EXACTLY one month? Or does the predicate hold for the input examples you provided just because 5 - 4 = 1? Anyway I think the code example below will give you the idea:

import java.time.LocalDate

def isOneMonthGreater(dateString1: String, dateString2: String): Boolean = 
  (LocalDate.parse(dateString1).getMonthValue - LocalDate.parse(dateString2).getMonthValue) == 1

You can also use ChronoUnit:

import java.time.LocalDate
import java.time.temporal.ChronoUnit

val d1 = LocalDate.parse("2022-05-23")
val d2 = LocalDate.parse("2022-04-24")
val d3 = LocalDate.parse("2022-04-23")

ChronoUnit.MONTHS.between(d2, d1)
// the above expression returns 0, since 29 days is actually 0 months!
ChronoUnit.MONTHS.between(d3, d1)
// this one returns 1

Also dates as strings is not a good practice most of the time, so having inputs of actual date types is more recommended.

Update:


Without conversion to date, you can parse it manually and there are many many ways to do this. And one thing to keep in mind is that as mentioned in comments, there might be some edge cases, but as far as I understood, this is just to explore around the language APIs.

  1. using regex. You can define the format you’re sure about for the date:
val pattern = "(\\d{4})-(\\d{2})-(\\d{2})".r
val dateString = "2022-03-02"

dateString match {
  case pattern(year, month, day) => ...
}

// or
val pattern(year, month, day) = dateString

But as mentioned, this is not safe, just to show that this approach exists.
2) splitting:

dateString.split("-")

And you can deal with the array elements as you wish.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading