1

Please check the below code. I am trying to get the difference but every time getting 0. Can anybody please point me what is the problem with below code?

SimpleDateFormat sDateFormat = new SimpleDateFormat("hh:mm:ss dd/mm/yyyy");
try {

    long d1 = sDateFormat.parse("10:04:00 04/04/2014").getTime();
    long d2 = sDateFormat.parse("10:09:00 04/04/2014").getTime();

    long difference = d2 - d1;

    Log.i(TAG,">> Difference = "+difference);

} catch (ParseException e) {
    e.printStackTrace();
}
Hamid Shatu
  • 9,664
  • 4
  • 30
  • 41
Hitendra
  • 3,218
  • 7
  • 45
  • 74

3 Answers3

4

your formatter does not fit the date format used.

Try:

new SimpleDateFormat("HH:mm:ss dd/MM/yyyy");
Hamid Shatu
  • 9,664
  • 4
  • 30
  • 41
light_303
  • 2,101
  • 2
  • 18
  • 35
1

From Android Developer documentation of SimpleDateFormat, you can see M is for Month and m is for minute...

M   month in year   (Text)      M:1 MM:01 MMM:Jan MMMM:January MMMMM:J
m   minute in hour  (Number)    30

So, you should change the date format from this...

hh:mm:ss dd/mm/yyyy

to this...

hh:mm:ss dd/MM/yyyy

I hope this format correction will solve your problem.

Hamid Shatu
  • 9,664
  • 4
  • 30
  • 41
0

Your format, hh:mm:ss dd/mm/yyyy has two problems:

  1. 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.
  2. 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.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110