1

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;
}
Lennie
  • 1,999
  • 4
  • 27
  • 42
  • possible duplicate of [parse this type of date format in java?](http://stackoverflow.com/questions/4013681/parse-this-type-of-date-format-in-java) – Matt Ball Sep 07 '11 at 20:03

3 Answers3

5

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.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • you have one small error on the pattern - It should be `HH` instead of `hh` since his example date time is in military time. Not nit-picking just pointing it out. :) – CoolBeans Sep 08 '11 at 00:35
  • Many thanks for the correction - fixed. That's [not the first time I've made this mistake](http://stackoverflow.com/questions/1313280/inconsistent-date-parsing-using-simpledateformat), either... – Matt Ball Sep 08 '11 at 01:15
  • Haha - that's quite a coincidence :) – CoolBeans Sep 08 '11 at 02:35
3

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");
CoolBeans
  • 20,654
  • 10
  • 86
  • 101
2

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

See any potential discrepancies? I see 3.

Alexx
  • 3,572
  • 6
  • 32
  • 39