51

I have two Date objects and I need to get the time difference so I can determine the total hours between them. They happen to be from the same day. The result I would like would have the hours and minutes.

When I use .toString() on my Date object I get this: Fri Dec 18 08:08:10 CST 2009

I've tried the following:

long diff = (this.endDate.getTime() - this.startDate.getTime()) / (60 * 60 * 1000);

But this only gives me hours, not the minutes. I know this is a simple problem, but I can't figure it out atm.

Edits: Final solution for those interested. Thanks to Michael Brewer-Davis

Period p = new Period(this.startDate, this.endDate);
long hours = p.getHours();
long minutes = p.getMinutes();
    
String format = String.format("%%0%dd", 2);
    
return Long.toString(hours) + ":" + String.format(format, minutes);
0

11 Answers 11

82

This should work.

long secs = (this.endDate.getTime() - this.startDate.getTime()) / 1000;
int hours = secs / 3600;    
secs = secs % 3600;
int mins = secs / 60;
secs = secs % 60;
1
  • may we add type cast before hours and mins like int hours = int(secs / 3600); Commented Mar 15, 2021 at 9:39
67

Here's how it works with Joda time:

DateTime startTime, endTime;
Period p = new Period(startTime, endTime);
int hours = p.getHours();
int minutes = p.getMinutes();

You could format with Joda's formatters, e.g., PeriodFormat, but I'd suggest using Java's. See this question for more details.

EDIT: be careful using this method to check hours between. This function don't respect days between. It get just hours between two times. 2022-07-20 11.00 and 2022-07-21 12.00 will return 1 hour, not 25 hours.

6
  • 1
    This is just about perfect. Thanks for the Joda Time link. But how to I get the display to be "H:mm" where H is hours and m minutes. For example "1:05". At the moment is would display "1:5"
    – clang1234
    Commented Jan 5, 2010 at 9:33
  • i am having result as zero in hours... Kindly help Commented Apr 12, 2013 at 9:16
  • 14
    Strangely Period did not work for me. I too got only 0 for all hours, even when the dates were days apart. Instead I used this: Hours hours = Hours.hoursBetween(startTime, endTime); I luckily needed only the hour, so this worked for me. Commented May 29, 2013 at 12:44
  • 8
    This only works because - as the OP indicated - start/end happens to be the same day. As other commenters have noted, it fails when using different dates. A Joda Period is divided into a number of fields and the getXXX methods only return the value of a specific field (e.g. for a period of 2 days, 2 hours, 30 minutes, getHours will return 2, not 50 (2*24+2). The correct way to "Find total hours between two Dates" with Joda is per Somaiah's comment.
    – hendalst
    Commented Apr 22, 2014 at 11:19
  • If I'm not mistaken, this isn't the total amount of hours, but the included amount of hours. When I have Period = P-2W-5DT-8H-30M-11.844S and ask for p.getHours(), it returns 8, instead of the total amount of hours for the 2 weeks, 5 days, etc. Commented Mar 7, 2017 at 14:31
14

Here's simple way:

private static int hoursDifference(Date date1, Date date2) {

    final int MILLI_TO_HOUR = 1000 * 60 * 60;
    return (int) (date1.getTime() - date2.getTime()) / MILLI_TO_HOUR;
}
1
  • 1
    Use DateTimeConstants.MILLIS_PER_HOUR if using joda time
    – Troveldom
    Commented May 26, 2014 at 14:22
13

java.time.Duration

I should like to contribute the modern (java 8+) answer. The solutions using Joda-Time are fine. The Joda-Time project is in maintenance mode, so for new code we should not use it. I follow the official recommendation from the Joda-Time project and use java.time, the modern Java date and time API:

    Duration dur = Duration.between(startDate, endDate);
    String result = String.format("%d:%02d", dur.toHours(), dur.toMinutesPart());
    System.out.println(result);

This works if startDate and endDate both have type Instant or OffsetDateTime or ZonedDateTime or LocalDateTime or LocalTime. All of the mentioned types are from java.time package. If starting with LocalDate, call either of the atStartOfDay methods.

The toMinutesPart methof was introduced in Java 9. If you are using Java 8 (ot ThreeTen Backport), search for java format duration or similar to learn how to format the duration into hours and minutes.

Two quotes from the Joda-Time home page:

Users are now asked to migrate to java.time (JSR-310).

Note that Joda-Time is considered to be a largely “finished” project. No major enhancements are planned. If using Java SE 8, please migrate to java.time (JSR-310).

Links

4

Please follow Somaiah's suggestion in a comment, use Hours instead:

Hours hours = Hours.hoursBetween(startTime, endTime);

The call to getHours() will only return the hour section of the time difference and ignore all year, month differences so it would not be correct in some cases.

If you use Period.toStandardHours() to try to convert the time difference into hours the calculation will throw an exception if the time difference between the two dates includes difference in either year or month, since the length of month is unknown.

1

Here's a pure Java 8+ solution that does not involve Joda or mathematical operations

import java.time.*;
import java.time.temporal.*;

// given two java.util.Dates
Date startDate ...
Date endDate ...

// convert them to ZonedDateTime instances
ZonedDateTime start = ZonedDateTime.ofInstant(startDate.toInstant(), ZoneId.systemDefault());
ZonedDateTime end = ZonedDateTime.ofInstant(endDate.toInstant(), ZoneId.systemDefault());

// get the total duration of minutes between them
Duration total = Duration.ofMinutes(ChronoUnit.MINUTES.between(start, end));

// use the duration to determine the hours and minutes values
long hours = total.toHours();
long minutes = total.minusHours(hours).toMinutes();
0

So the getTime() method, I presume, returns an integer.

In which case, the left set of parentheses has type int, right?

and

(60*60*1000)

is also an int.

Which means you get long diff = ((int)/(int)) so the integer division is done BEFORE you cast stuff to long. And hence you lose your minutes.

Try casting them BEFORE you divide.

2
  • The getTime() method returns a Long not an int.
    – clang1234
    Commented Jan 5, 2010 at 1:24
  • Ah... Then what Rob Van Dam said, I think. Also what Gregs said. Commented Jan 5, 2010 at 1:47
0

for kotlin, you can use below function and get hours between two date

private val dateFormat: String = "yyyy-MM-dd @ hh:mm a"
val startDate = SimpleDateFormat(dateFormat).parse("2018-10-01 @ 12:33 PM")
val endDate = SimpleDateFormat(dateFormat).parse("2018-10-01 @ 02:46 PM")

private fun hoursDifference(date1: Date, date2: Date): Int {
    val milliToHour : Long = 1000 * 60 * 60
    return ((date1.time - date2.time) / milliToHour).toInt()
}

println(hoursDifference(endDate,startDate).toString())

Output: 2

0

Even though there's already an accepted answer, this is what worked for me using the Joda time library.

/**
 *
 * @param date1
 * @param date2
 * @return hours between two dates rounded down
 */
public static int hoursBetween(DateTime date1, DateTime date2) {
    if(date1 == null || date2 == null) return NOT_FOUND;

    return Math.abs(Hours.hoursBetween(date1.toLocalDateTime(), date2.toLocalDateTime()).getHours());
}
0
private void getHours(Date d1, Date d2){
long diff = d2.getTime() - d1.getTime();

  long diffSeconds = diff / 1000 % 60;
        long diffMinutes = diff / (60 * 1000) % 60;
  long diffDays = diff / (24 * 60 * 60 * 1000);
        long diffHours = diff / (60 * 60 * 1000) % 24;

        System.out.print(diffDays + " days, ");
        System.out.print(diffHours + " hours, ");
        System.out.print(diffMinutes + " minutes, ");
        System.out.print(diffSeconds + " seconds.\n");

}`

//Displays: /* 1 days, 1 hours, 1 minutes, 50 seconds. */

-2

Here is the simple method :- Check your Date format,if your date not in this format then change it and pass to this method it will give you a String which is your result. Modify the method as per the requirement.

private String getDateAsTime(String datePrev) {
        String daysAsTime = "";
        long day = 0, diff = 0;
        String outputPattern = "yyyy:MM:dd HH:mm:ss";
        SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);
        Calendar c = Calendar.getInstance();
        String dateCurrent = outputFormat.format(c.getTime());
        try {
           Date  date1 = outputFormat.parse(datePrev);
            Date date2 = outputFormat.parse(dateCurrent);
            diff = date2.getTime() - date1.getTime();
            day = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (day == 0) {
            long hour = TimeUnit.HOURS.convert(diff, TimeUnit.MILLISECONDS);
            if (hour == 0)
                daysAsTime = String.valueOf(TimeUnit.MINUTES.convert(diff, TimeUnit.MILLISECONDS)).concat(" minutes ago");
            else
                daysAsTime = String.valueOf(hour).concat(" hours ago");
        } else {
            daysAsTime = String.valueOf(day).concat(" days ago");
        }
        return daysAsTime;
    }

Hope this will help,

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.