Hitendra
Hitendra

Reputation: 3226

Not able to get difference between two datetime?

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();
}

Upvotes: 1

Views: 80

Answers (3)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79015

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.

Upvotes: 0

Hamid Shatu
Hamid Shatu

Reputation: 9700

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.

Upvotes: 1

light_303
light_303

Reputation: 2111

your formatter does not fit the date format used.

Try:

new SimpleDateFormat("HH:mm:ss dd/MM/yyyy");

Upvotes: 4

Related Questions