Arvinth
Arvinth

Reputation: 70

Subtract Months from YYYYMM date in Scala

I am trying to subtract months from YYYYMM format.

import java.text.SimpleDateFormat

val date = 202012
val dt_format = new SimpleDateFormat("YYYYMM")
val formattedDate = dt_format.format(date)
new DateTime(formattedDate).minusMonths(3).toDate();

Expected output:

202012 - 3 months = 202009,
202012 - 14 months = 201910

But it did not work as expected. Please help!

Upvotes: 1

Views: 1974

Answers (2)

stefanobaghino
stefanobaghino

Reputation: 12794

This solution uses the functionality in java.time, available since Java 8. I would have preferred coming up with a solution that did not require to adjust the input so that it could be (forcefully) parsed into a LocalDate (so that plusMonths) could be used, but at least it works.

Probably a simple regex could get the job done. ;-)

import java.time.format.DateTimeFormatter
import java.time.LocalDate

val inFmt = DateTimeFormatter.ofPattern("yyyyMMdd")
val outFmt = DateTimeFormatter.ofPattern("yyyyMM")

def plusMonths(string: String, months: Int): String =
  LocalDate.parse(s"${string}01", inFmt).plusMonths(months).format(outFmt)

assert(plusMonths("202012", -3) == "202009")
assert(plusMonths("202012", -14) == "201910")

You can play around with this code here on Scastie.

Upvotes: 2

darw
darw

Reputation: 1057

Among standard date/time types YearMonth seems to be the most appropriate for the given use case.

import java.time.format.DateTimeFormatter
import java.time.YearMonth

val format = DateTimeFormatter.ofPattern("yyyyMM")

YearMonth.parse("197001", format).minusMonths(13) // 1968-12

Upvotes: 3

Related Questions