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?
4 Answers
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
Your DateFormat pattern does not match you input date String. You could use
new SimpleDateFormat("dd-MMM-yyyy")
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.
//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.