Lennie
Lennie

Reputation: 2069

Parse A Java Date

How can I parse the following date in Java from its string representation to a java.util.Date?

2011-07-12T16:45:56

I tried the following:

private Date getDateTime(String aDateString) {
    Date result = new java.util.Date();
    SimpleDateFormat sf = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
    try
    {
        result = sf.parse(aDateString);
    }
    catch (Exception ex)
    {
        Log.e(this.getClass().getName(), "Unable to parse date: " + aDateString);
    }
    return result;
}

Upvotes: 1

Views: 660

Answers (3)

Matt Ball
Matt Ball

Reputation: 359786

You are not using the right date format pattern. The year/month/day separators are clearly wrong, and you need a literal 'T'. Try this:

SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

For the record, this is an ISO 8601 combined date and time format.

Upvotes: 5

Alexx
Alexx

Reputation: 3692

Check the pattern you are feeding your SimpleDateFormat against the string you are feeding in.

See any potential discrepancies? I see 3.

Upvotes: 2

CoolBeans
CoolBeans

Reputation: 20800

Your date format pattern is incorrect. It should be yyyy-MM-dd'T'HH:mm:ss .

To parse a date like "2011-07-12T16:45:56" you need to use:-

SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

Upvotes: 3

Related Questions