-2

I have two String variables containing values "201703" and "201506" respectively i.e. the values are of the format "yyyyMM" but variables of type String. I want to find out the difference between those two dates in number months using Scala and JDK 8.

Example inputs:

val x = "201506"
val y = "201703"

Desired output:

21    
Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93
Rajdip
  • 49
  • 1
  • 10
  • It’s sort of a duplicate of [Java Date month difference](https://stackoverflow.com/questions/1086396/java-date-month-difference). – Ole V.V. May 24 '18 at 14:28

1 Answers1

5

This can be done easily with Java Time.

  import java.time.YearMonth
  import java.time.format.DateTimeFormatter
  import java.time.temporal.ChronoUnit._

  val date1 = "201506"
  val date2 = "201703"

  val formatter = DateTimeFormatter.ofPattern("yyyyMM")

  val ym1 = YearMonth.parse(date1, formatter)
  val ym2 = YearMonth.parse(date2, formatter)

  val months = ym1.until(ym2, MONTHS)
Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93
peterschrott
  • 570
  • 5
  • 25