-1

I have a String of yyyyMM format and I need to convert it to a date in the format MM/yyyy.

Example: String is 201710 and it needs to be converted to a date in the format 10/2017.

Can someone tell me how to do this in ?

Thanks

Szymon Stepniak
  • 40,216
  • 10
  • 104
  • 131
user2993178
  • 97
  • 1
  • 12
  • Possible duplicate of [Groovy String to Date](https://stackoverflow.com/questions/3817862/groovy-string-to-date) – injecteer Jan 11 '18 at 10:30

1 Answers1

0

There is no such thing as java.util.Date object in specific format. Format of the date like yyyyMM or MM/yyyy is just a way it is represented as a String. If your input is a String formatted as 201710 and you want to format it as 10/2017 then you have to create a java.util.Date object from your input String (Date.parse() method does that) and call .format('MM/yyyy') method on that created object, e.g.

def formatted = Date.parse("yyyyMM", "201710").format("MM/yyyy")
Szymon Stepniak
  • 40,216
  • 10
  • 104
  • 131
  • I set the current date to the formatted value (10/2017) using acalendar.setTime(formatted) and then tried to get the month using int month =acalendar.get(Calendar.MONTH). This returns an error ' Cannot cast object '10/2017' with class 'java.lang.String' to class 'java.util.Date' '. Is there a way to convert 'formatted ' to Date ? – user2993178 Jan 11 '18 at 11:15
  • Following part creates `java.util.Date` object - `Date.parse("yyyyMM", "201710")`. If you want to pass it to `Calendar.setTime()` then don't call `.format("MM/yyyy")` on this object, because this method returns a `String`. – Szymon Stepniak Jan 11 '18 at 11:41
  • Yes, it works now. Date formatted = Date.parse("yyyyMM", "201710") acalendar.setTime(formatted) Thanks Szymon ! – user2993178 Jan 11 '18 at 11:47