56

I'm new to Java/Groovy development and I have a simple string that I would like to reformat, however I get an 'Unparseable date' error when I attempt to run the following:

import java.text.SimpleDateFormat 
import java.util.Date

String oldDate
Date date
String newDate 

oldDate = '04-DEC-2012'
date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(oldDate)
newDate = new SimpleDateFormat("M-d-yyyy").format(date) 

println newDate

I'm sure it's something simple, but the solution eludes me. Can anyone help?

DC Guy
  • 563
  • 1
  • 4
  • 4
  • 1
    Your date is given in "DD-MMM-YYYY" pattern, and you are trying to parse something else... – posdef Jan 17 '13 at 16:21
  • duplicate http://stackoverflow.com/questions/11135675/unparseable-date-30-jun-12 – CAMOBAP Jan 17 '13 at 16:22
  • Not knowing Grrovy for new readers to this question I strongly recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDate`, `DateTimeFormatterBuilder` and `DateTimeFormatter`, all from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). See [this answer by user7605325](https://stackoverflow.com/a/46645976/5772882). – Ole V.V. May 16 '22 at 17:13

4 Answers4

88

With Groovy, you don't need the includes, and can just do:

String oldDate = '04-DEC-2012'
Date date = Date.parse( 'dd-MMM-yyyy', oldDate )
String newDate = date.format( 'M-d-yyyy' )

println newDate

To print:

12-4-2012
tim_yates
  • 161,005
  • 26
  • 328
  • 327
  • 2
    @Andreas 7 years later, the link is http://docs.groovy-lang.org/docs/groovy-2.4.4/html/groovy-jdk/java/util/Date.html#parse(java.lang.String,%20java.lang.String) – tim_yates Jun 26 '20 at 10:18
3

Your DateFormat pattern does not match you input date String. You could use

new SimpleDateFormat("dd-MMM-yyyy")
Reimeus
  • 155,977
  • 14
  • 207
  • 269
1

oldDate is not in the format of the SimpleDateFormat you are using to parse it.

Try this format: dd-MMM-yyyy - It matches what you're trying to parse.

Jesan Fafon
  • 2,094
  • 1
  • 23
  • 29
0
//Groovy Script

import java.util.Date   
import java.util.TimeZone   
tz = TimeZone.getTimeZone("America/Sao_Paulo")   
def date = new Date()   
def dt = date.format("yyyy-MM-dd HH:mm:ss", timezone=tz)   
println dt //formatado   
println date // formatado porém, horario do Sistema em GMT.
  • 2
    Thanks for wanting to contribute. I strongly recommend you don’t use `Date` and `TimeZone`. Those classes are poorly designed and long outdated. Instead use classes from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). Also and quite importantly, in what way does your answer answer the question? I believe the question was about reformatting from a format like `04-DEC-2012` into `12-4-2012`. – Ole V.V. May 16 '22 at 17:15