Unable to convert the String format to a Java Date. It is not
identifying the time as AM/PM
You are asking the impossible. A Date
is a point in time (internally implemented as a count of milliseconds since the so-called epoch), so it “knows” nothing about AM and PM in your time zone.
That’s just the same, though, because the Date
class was always poorly designed and is fortunately long outdated. You should not use it at all.
java.time
java.time, the modern Java date and time API that we should use instead of Date
, comes closer to fulfilling your requirement. MC Emperor has already shown the basic code you need for parsing your datetime string. The output from his code is:
2010-01-01T15:23:12Z
There’s no AM or PM here. When we print an OffsetDateTime
in this way, its toString
method is implicitly called. It produces an ISO 8601 formatted string. ISO 8601 prescribes a 24 hour clock (no AM or PM). But! With assistance from the correct TemporalField
object the OffsetDateTime
is able to calculate and return whether it is in AM or PM. time.get(ChronoField.AMPM_OF_DAY)
returns 0 for AM or 1 for PM:
System.out.println("AM or PM? 0 for AM. 1 for PM. time: "
+ time.get(ChronoField.AMPM_OF_DAY));
AM or PM? 0 for AM. 1 for PM. time: 1
So in this case we got 1 for PM as expected since your original string had PM
in it.
I have deliberately not answered all of your question because much of it has been covered in other Stack Overflow questions and their answers already. So it’s better to keep the information there. I include links to a couple of relevant questions below.
What went wrong in your code?
There are at least two bugs in your code that each cause you to get an incorrect result. I tried running your code in America/Los_Angeles time zone and got
Fri Jan 01 03:23:12 PST 2010
The time printed is on a 24 hour clock (Date
always does that), so we got 03:23:12 AM instead of PM. And we got the time in the default time zone (PST is for Pacific Standard Time), so the point in time corresponds to 11:23:12 AM at offset +00:00, the offset in the string.
- The wrong clock hour comes from conflicting indications in your code:
HH
in the format pattern string is for hour of day from 00 through 23, so 3
is taken to mean 03 AM and apparently “wins” over the PM marker (for hour within AM or PM, from 1 through 12, you would have needed lowercase h
).
- The default time zone comes from the fact that you are making no attempt to parse the offset from the string (in conjunction with
SimpleDateFormat
being satisfied with not parsing all of the string).
Links