Parsing and Formatting a Date in Groovy/Grails
Feb 27, 2021
If you have a string variable containing a date value such as 2014–06–03T11:03:44.779+03, then:
- Convert it to Date using “parse” method of SimpleDateFormat
- Format the Date using the format you want such as “yyyy-MM-dd” or “yyyy/MM/dd” or any other.
Code Example
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)/* Simplified code in one line
Date parsedAndFormattedDate = formatter.format(formatter.parse(mydate))
*/
Originally published at http://binyit.blogspot.com.