The format string should match the input. In particular, the separator must match.
Also, your format string is missing the time zone part to match against the -0800
.
Since your input uses English month name, you should explicitly specify that, e.g. using Locale.US
.
SimpleDateFormat f = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z", Locale.US);
Date d = f.parse("07/Mar/2004:16:56:39 -0800");
System.out.println(d);
Since I'm in Eastern time zone, that prints:
Sun Mar 07 19:56:39 EST 2004
You should however use the new java.time
classes instead.
Since the input string has a time zone offset, that means you should parse the string to an OffsetDateTime
, using a DateTimeFormatter
:
DateTimeFormatter f = DateTimeFormatter.ofPattern("dd/MMM/uuuu:HH:mm:ss Z", Locale.US);
OffsetDateTime dt = OffsetDateTime.parse("07/Mar/2004:16:56:39 -0800", f);
System.out.println(dt);
Output is:
2004-03-07T16:56:39-08:00