41

I've tried different methods around the web but couldn't make it work.

Cursor cursor = sqlite.myDataBase.rawQuery("SELECT StartDate, EndDate FROM Tracks Where Id="+'"'+trackId+'"',null);

SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date startDate = outputFormat.parse(cursor.getString(cursor.getColumnIndex("StartDate")));
Date endDate = outputFormat.parse(cursor.getString(cursor.getColumnIndex("EndDate")));

In this way I get both dates in good format. Now I want to find the difference between EndDate and Startdate in seconds.

Any advice? Thank you.

Vasily Kabunov
  • 6,511
  • 13
  • 49
  • 53
Alin
  • 14,809
  • 40
  • 129
  • 218

4 Answers4

126

You can turn a date object into a long (milliseconds since Jan 1, 1970), and then use TimeUnit to get the number of seconds:

long diffInMs = endDate.getTime() - startDate.getTime();

long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMs);

Edit: -Corrected the name of the variable diffInMs which was written diffInM(i)s in the second line.

Cheryl Simon
  • 46,552
  • 15
  • 93
  • 82
6

try below method:-

    public String twoDatesBetweenTime(String oldtime)
    {
        // TODO Auto-generated method stub
        int day = 0;
        int hh = 0;
        int mm = 0;
        try
        {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date oldDate = dateFormat.parse(oldtime);
            Date cDate = new Date();
            Long timeDiff = cDate.getTime() - oldDate.getTime();
            day = (int) TimeUnit.MILLISECONDS.toDays(timeDiff);
            hh = (int) (TimeUnit.MILLISECONDS.toHours(timeDiff) - TimeUnit.DAYS.toHours(day));
            mm = (int) (TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff)));
        }
        catch (ParseException e)
        {
            e.printStackTrace();
        }
        if(day==0)
        {
            return hh + " hour " + mm + " min";
        }
        else if(hh==0)
        {
            return mm + " min";
        }
        else
        {
            return day + " days " + hh + " hour " + mm + " min";
        }
    }
duggu
  • 37,851
  • 12
  • 116
  • 113
  • this fails if my old date is 2018-05-8 12:05:00 and the current date is 2018-05-9 12:37:00 this does not show the day difference – Akshay Katariya May 09 '18 at 07:12
  • Yes this fails if my old date is 2018-08-30 16:34:54 and current date is 2018-09-01 20:50:07 then difference in milliseconds are coming in negative – Satendra Baghel Sep 01 '18 at 10:51
5

Just complementing this answer for other developers (like me) who are using Time instead of Date.

Time t1 = new Time();
t1.setToNow();
Thread.sleep(1000);

Time t2 = new Time();
t2.setToNow();

diff = TimeUnit.MILLISECONDS.toSeconds(t2.toMillis(true)-t1.toMillis(true));
António Almeida
  • 9,620
  • 8
  • 59
  • 66
Igor Zelaya
  • 4,167
  • 4
  • 35
  • 52
  • Is that [`android.text.format.Time`](https://developer.android.com/reference/android/text/format/Time)? (Deprecated since API level 22) – Ole V.V. Mar 10 '20 at 05:23
2

While the other answers work and were fine answers in 2010, I am providing the modern answer.

java.time and ThreeTenABP

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
    ZoneId zone = ZoneId.systemDefault();

    String startDateString = "2019-12-31 23:34:45";
    String endDateString = "2020-01-01 07:56:34";

    ZonedDateTime start = LocalDateTime.parse(startDateString, formatter).atZone(zone);
    ZonedDateTime end = LocalDateTime.parse(endDateString, formatter).atZone(zone);

    long diffSeconds = ChronoUnit.SECONDS.between(start, end);

    System.out.println("Difference: " + diffSeconds + " seconds");

In most time zones output from this snippet will be:

Difference: 30109 seconds

I am using ZonedDateTime because it takes transitions to and from summer time (DST) and other time anomalies into account. It requires that you use the correct time zone, of course. If the time zone setting of your device is changed since you stored the dates and times into your database, you risk some surprises. To prevent such, you may store a UTC offset along with your times and then parse them into OffsetDateTime on retrieval.

Question: Doesn’t java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161