user1949565
user1949565

Reputation:

Convert string into a Java Date

String stringDate = "2013-08-20T12:10:35Z"

How can I convert this stringDate into a Date? I have tried the following:

def dateString = stringDate.replace("T",":")
Date date = new Date().parse("yyyy-M-d:H:m:s", dateString)

The result is not correctly formatted and the parse is deprecated for date.

Upvotes: 2

Views: 2277

Answers (3)

Veronica Cornejo
Veronica Cornejo

Reputation: 488

You need to set up a Java SimpleDateFormat object and then call its parse method.

SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;
Date result= sdf.parse(input) ;

Check SimpleDateFormat documentation for format options.

Upvotes: 2

ataylor
ataylor

Reputation: 66069

The Java method static long parse(String s) is deprecated, but groovy provides a non-deprecated parse method:

def date = Date.parse("yyyy-MM-dd'T'HH:mm:ss'Z'", stringDate)

The format you're using is the ISO 8601 standard format. Searching on that should provide you with additional information.

Upvotes: 4

ubiquibacon
ubiquibacon

Reputation: 10667

Make your life easier, use the Grails Joda Time plugin.

http://grails.org/plugin/joda-time

Upvotes: 0

Related Questions