Tuesday, June 3, 2014

Parsing and Formatting a Date in Groovy/Grails

If you have a string variable containing a date value such as 2014-06-03T11:03:44.779+03, then:

First -  Convert it to Date using "parse" method of SimpleDateFormat
Seond - Format the Date using the format you want such as "yyyy-MM-dd" or "yyyy/MM/dd" or any other.

Code

import java.text.SimpleDateFormat
import java.text.DateFormat

String mydate = "2014-06-03T11:03:44.779+03"

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd")

Date parsedDate = formatter.parse(mydate)

Date formattedDate = formatter.format(parsedDate)

/* In one line
    Date parsedAndFormattedDate  =  formatter.format(formatter.parse(mydate))
*/