I ran into an issue while parsing the following date.
08 März 2015 02:15:20
Code
SimpleDateFormat fmt = new SimpleDateFormat("dd MMM yyyy HH:mm:ss", Locale.GERMAN);
fmt.setLenient(false);
try {
System.out.println(fmt.parse("08 März 2015 02:15:20"));
} catch (ParseException e) {
e.printStackTrace();
}
After some investigation, I found out that due to how DST works, 2 AM in my timezone does not exist. Once the clock strikes 1:59 AM, the next time it updates will be 3 AM. I have checked that this is the case with the following dates:
"08 März 2015 01:59:59"
"08 März 2015 03:00:00"
Both of which can be parsed correctly.
What I want is a date object that correctly interprets the input date exactly as I see it:
Mar 8, 2015 at 2:15:20 AM
How can I accomplish this?
Ideally, you'd use a parser that allowed you to parse date/time values without trying to apply a time zone at all - both java.time.*
and Joda Time allow for this, IIRC, and both are much cleaner than java.util.*
.
However, if you have to use Date
, and you don't know the origin time zone, the safest approach is to use TimeZone
:
SimpleDateFormat parser = new SimpleDateFormat(
"dd MMM yyyy HH:mm:ss",
Locale.GERMAN);
parser.setLenient(false);
parser.setTimeZone(TimeZone.getTimeZone("UTC"));
So, that will parse it as if it were originally in UTC - so when you want to format it back to text, you need to do the same thing:
SimpleDateFormat formatter = new SimpleDateFormat(
"EEE d, yyyy at h:mm:ss tt",
Locale.US);
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String text = formatter.format(date);
See more on this question at Stackoverflow