Your format, hh:mm:ss dd/mm/yyyy
has two problems:
h
is used for 12-Hour time format i.e. a time format with AM/PM marker which is not the case with your date-time strings. You need to use H
which is used for a 24-Hour time format.
m
is not used for a month. For a month, you need to use M
.
Apart from this, the legacy date-time API (java.util
date-time types and their formatting API, SimpleDateFormat
) are outdated and error-prone. It is recommended to stop using them completely and switch to java.time
, the modern date-time API*.
Demo using modern date-time API:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String args[]) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("H:m:s d/M/u");
LocalDateTime start = LocalDateTime.parse("10:04:00 04/04/2014", dtf);
LocalDateTime end = LocalDateTime.parse("10:09:00 04/04/2014", dtf);
long diff = ChronoUnit.MILLIS.between(start, end);
System.out.println(diff);
}
}
Output:
300000
Learn more about the the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.