Does anyone know why Date is losing time values when converting from String ? I cannot seem to figure this one out.
Here is what type of SimpleDateFormat
I am using:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MM/dd/yyyy HH:mm a");
The date I am trying to convert is a String in the form :
String dateString = "Mon 06/23/2014 03:00 PM";
And when I do the following:
Date convertDateFromString = null;
try{
convertDateFromString = simpleDateFormat.parse(dateString);
}catch(ParseException ex){
ex.printStackTrace();
}
System.out.println(convertDateFromString.getTime());
My output is: 1403496000000
And the expected output is: 1403550000000
Can someone help me understand why the time is not being parsed?
Update - Solved --->> with the help of Jon Skeet
now using this SimpleDateFormat
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MM/dd/yyyy hh:mm a", Locale.getDefault());
and now the output is correct.
You've specified HH
in your format, which is the 24-hour format. But you've also got an AM/PM designator.
As such, "03:00 PM" doesn't make sense - it's simultaneously trying to represent 3am (03 in 24 hours) and 3pm (PM in the data).
It sounds like you probably want hh
in the format string, as the 12-hour specifier.
That's part of the problem. Next up is the time zone. Your expected value (1403550000000) represents 2014-06-23 19:00:00Z. So presumably you're expecting to use a time zone which is currently 4 hours behind UTC.
Your actual value (1403496000000) at the moment is 2014-06-23 04:00:00Z... so it appears to being parsed in a time zone which is 1 hour behind UTC.
You need to work out which time zone that data is meant to be in, and specify it explicitly in the SimpleDateFormat
.
See more on this question at Stackoverflow