2

My code to get the calendar date frone the string "2018-04-14'T'15:38:14", it is currently causing a exception WHEN i call setTime. The code

    Calendar cal = Calendar.getInstance();
    // format of date yyyy-MM-dd'T'HH:mm:ss
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd 'T' 
    cal.setTime(sdf.parse("2018-04-14'T'15:38:14"));// all done1 

The above line causes a exception saying "Unparsable date"

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Ted pottel
  • 6,869
  • 21
  • 75
  • 134
  • 3
    this doesnt compile. you seem to have some code missing from your question – Reimeus Apr 15 '18 at 17:12
  • I recommend you avoid the `SimpleDateFormat` class. It is not only long outdated, it is also notoriously troublesome. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Apr 15 '18 at 17:41
  • Stacktrace, please? It would show you that the exception doesn’t come from `setTime`, but from `parse`. – Ole V.V. Apr 15 '18 at 17:42
  • 1
    Don’t tell me there are apostrophes in the string you need to parse? Surely it’s `2018-04-14T15:38:14`, not `2018-04-14'T'15:38:14`?? – Ole V.V. Apr 16 '18 at 04:29

1 Answers1

1

'T' is a constant. Notice the subtle difference. The format is defined with T in single quotes but when you pass the value, it's without.

Calendar cal = Calendar.getInstance();
// format of date yyyy-MM-dd'T'HH:mm:ss
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
cal.setTime(sdf.parse("2018-04-14T15:38:14"));// all done1
geco17
  • 5,152
  • 3
  • 21
  • 38
  • 2
    and there are some whitespaces in OP's format that you removed that *might* have caused issues as well – luk2302 Apr 15 '18 at 17:16