You have to adjust your pattern:
- use single-digit months of year (and maybe even days of month, hours of day, minutes of hour and seconds of minute)
- escape the
T
by enclosing it in single quotes
You can do that the modern way (since Java 8) or the outdated way (not recommended).
Here are two examples, one for each way:
Modern way (java.time
)
public static void main(String[] args) {
String input1 = "12-1-2012 T 10:23:34";
String input2 = "12-01-2012 T 10:23:34";
// define your pattern)
String format = "d-M-uuuu 'T' H:m:s";
// define a DateTimeFormatter from the pattern
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(format);
// parse both of the Strings using the defined formatter
LocalDateTime ldt1 = LocalDateTime.parse(input1, dtf);
LocalDateTime ldt2 = LocalDateTime.parse(input2, dtf);
// print a result
System.out.println(ldt1 + " and " + ldt2 + " are "
+ (ldt1.equals(ldt2) ? "equal" : "not equal"));
}
Output
2012-01-12T10:23:34 and 2012-01-12T10:23:34 are equal
Outdated way (java.util
and java.text
)
public static void main(String[] args) throws ParseException {
String input1 = "12-1-2012 T 10:23:34";
String input2 = "12-01-2012 T 10:23:34";
// define your pattern
String format = "d-M-yyyy 'T' H:m:s";
try {
// create a SimpleDateFormat from the pattern
SimpleDateFormat sdf = new SimpleDateFormat(format);
// parse both of the Strings using the date format
Date date1 = sdf.parse(input1);
Date date2 = sdf.parse(input2);
System.out.println(date1 + " and " + date2 + " are "
+ (date1.equals(date2) ? "equal" : "not equal"));
} catch (ParseException e) {
e.printStackTrace();
throw(e);
}
}
Output
Thu Jan 12 10:23:34 CET 2012 and Thu Jan 12 10:23:34 CET 2012 are equal
Please note that the outdated way magically added a time zone, which is CET due to this code executed on my German machine…
For datetimes with zones or offsets, you will have to use different classes in java.time
, such as ZonedDateTime
and OffsetDateTime
.