0

I need to get time difference in my program. ex: if user inserts earlier time as 08:30 and later time as 5:00 I need to calculate the time gap as 8 hours and 30 minutes(I want it to display as 08 hours 30 min)

I'm using phpmyadmin and my db has employee table,and in it there are three columns as earlierTime,laterTime and noOfHoursWorked and all these columns' data types are varchar(50) so i did this but output is not correct

public String timeDifference(String  earlierTime, String laterTime) {
    SimpleDateFormat format = new SimpleDateFormat("HH:mm");
    Date date1 = format.parse(startTime);
    Date date2 = format.parse(leavedTime);
    long difference = date2.getTime() - date1.getTime();
    String d = String.valueOf(difference);
    return d;
}

can anyone please tell me what is wrong here I'm struggling with this problem for hours now

Is it okay if i change earlierTime, laterTime as date and noOfHoursWorked as int then i know in my output i can't get "8 hours 30 minutes" as output,so that I'd like to see it as "08:30"

  • 5
    Use Java 8's Time API or Joda-Time, something like [this](http://stackoverflow.com/questions/12851934/how-to-find-difference-between-two-joda-time-datetimes-in-minutes/12852021#12852021) for example – MadProgrammer Sep 09 '15 at 11:37
  • Provide actual and expected results – Basilevs Sep 09 '15 at 11:39
  • 2
    `earlierTime, laterTime and noOfHoursWorked ... all these columns' data types are varchar(50)` Why? You should store dates and times as dates and times, not strings. – takendarkk Sep 09 '15 at 11:40
  • Currently you're getting the difference in milliseconds, and just converting that into a string. That's not going to be in the format of "08 hours 30 min", clearly. Have you tried working out how to convert milliseconds into a number of hours and minutes? Ignore the string part to start with. And I agree with Takendarkk - using string fields here seems like a bad idea. – Jon Skeet Sep 09 '15 at 11:43
  • Joda-Time can help you: here's a similar SO question: http://stackoverflow.com/questions/1555262/calculating-the-difference-between-two-java-date-instances – Miroslav Lazovich Sep 09 '15 at 11:52
  • This can be very easily done,just specify AM and PM. – Sumeet Sep 09 '15 at 12:28
  • how to do that please show me a example code –  Sep 09 '15 at 13:33

2 Answers2

2

java.time

In Java 8 and later use the java.time package. (Tutorial)

// Some exemplary dates
Calendar cal = Calendar.getInstance();
cal.set(2015, 9, 9, 10, 15, 0);
Date date1 = cal.getTime();
cal.set(2015, 9, 9, 14, 0, 20);
Date date2 = cal.getTime();

Duration duration = Duration.between(date1.toInstant(), date2.toInstant());
System.out.println(duration.toMinutes());

long minutes = duration.toMinutes()%60;
long hours = duration.toMinutes() / 60;
System.out.println("Duration " + hours + ":" + minutes);

long minutes = duration.toMinutes()%60;
long hours = duration.toMinutes() / 60; // this takes the math floor be default
System.out.println("Duration " + hours + ":" + minutes);

Joda-Time

In older Java, if only you can easily add external libraries, use Joda-Time. It's the best solution, since many peoples' workarounds do not take leap years into account while calculating date differences.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
AndrewMcCoist
  • 609
  • 4
  • 12
  • 2
    Why use java.util.Date/.Calendar in the first part? Stick with java.time all the way through. Plus better to specify a time zone than rely implicitly on the JVM’s current default time zone. `ZoneId zoneId = ZonedId( "America/Montreal" );` ( or `ZoneId.systemDefault()` ) and `ZonedDateTime start = ZonedDateTime.of( 2015 , 9 , 9 , 10 , 15 , 0 , zoneId );` – Basil Bourque Sep 10 '15 at 03:34
1

take a look at this :

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDifferentExample {

 public static void main(String[] args) {

    String dateStart = "01/14/2012 09:29:58";
    String dateStop = "01/15/2012 10:31:48";

    //HH converts hour in 24 hours format (0-23), day calculation
    SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

    Date d1 = null;
    Date d2 = null;

    try {
        d1 = format.parse(dateStart);
        d2 = format.parse(dateStop);

        //in milliseconds
        long diff = d2.getTime() - d1.getTime();

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

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

    } catch (Exception e) {
        e.printStackTrace();
    }

}

}

  • from this i got the expected output but i'm confused why you are using (modulus sign %) long diffMinutes = diff / (60 * 1000) % 60; long diffHours = diff / (60 * 60 * 1000) % 24; diff is in milliseconds so we diff / (60 * 1000) is used to convert milliseconds to minutes but then what is the purpose of using % 60 can anyone please explain this –  Sep 09 '15 at 14:00
  • 1
    If you change it to long diffSeconds = diff / 1000; The result will be 1 days, 1 hours, 1 minutes, 90110 seconds. The “90110” is the total number of seconds difference between date1 and date2, this is correct if you want to know the differences in seconds ONLY. To display difference in “day, hour, minute and second” format, you should use a modulus (%60) to cut off the remainder of seconds (90060). Got it? The idea is applied in minutes (%60) and hours (%24) as well. 90110 % 60 = 50 seconds (you want this) 90110 - 50 = 90060 seconds (you dont want this) – felli mohamed hedi Sep 09 '15 at 15:15
  • @fellimohamedhedi feel free for any queries. – Sumeet Sep 09 '15 at 17:42