user594720
user594720

Reputation: 449

Calculate the difference b/w two given times in java

I am trying to calculate the difference between given two times and i find some problem in it. Suppose we have times value are "11:AM" and 10:00 AM". I am able to calculate but there is a bit of confusion in AM ,PM. Thanks in advance

I am using following code:

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

public class StringToDate {

public static String timeDiff(String time1, String time2) {
    String Time = null;
    int difference;
    String a1 = time1.substring(6);
    String a2 = time2.substring(6);

    try {
        // Define a date format the same as the expected input
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm a");
        // Get time values of the date objects
        long l1 = sdf.parse(time1).getTime();
        long l2 = sdf.parse(time2).getTime();
        difference = (int) (l2 - l1);
        difference = (difference < 0 ? -difference : difference) / 60000;
        if (difference > 60) {
            int Hour = difference / 60;
            int Mins = difference % 60;
            if (Mins == 0)
                Time = Hour + " Hours";
            else
                Time = Hour + " Hours" + " " + Mins + " Mins";
        } else {
            Time = difference + " " + "Mins";
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return Time;
}

public static void main(String[] args) {
    String diff = StringToDate.timeDiff("10:00 AM", "01:00 PM");
    System.out.println("Difference: " + diff);
}

}

Upvotes: 1

Views: 4471

Answers (5)

р&#252;ффп
р&#252;ффп

Reputation: 5448

For String / Date conversion and / or calculation I recommend you the utilities of Apache Commons: https://commons.apache.org/lang/api-2.6/index.html

  • StringUtils
  • DateUtils
  • DateFormatUtils

Always useful and no need to reinvent the wheel...

Update: I recently used another library: JodaTime which was very useful for all the date manipulation.

Upvotes: 0

Virginia Le&#243;n
Virginia Le&#243;n

Reputation: 21

To calculate the difference between two times in 12 hour AM/PM format, try this:

     try {
        SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss a"); 

        Date d1 = format.parse("11:59:30 PM");
        Date d2 = format.parse("12:01:00 AM");

        System.out.println("=== Start* :: "+ timeStart);
        System.out.println("=== End*   :: "+ timerEndOrCurrent);

        long difference = d2.getTime() - d1.getTime(); 
        int days = (int) (difference / (1000*60*60*24));  
        int hours = (int) ((difference - (1000*60*60*24*days)) / (1000*60*60)); 
        long min = (int) (difference - (1000*60*60*24*days) - (1000*60*60*hours)) / (1000*60);
        hours =  (hours < 0 ? -hours : hours);
        long sec = (int) (difference / 1000) % (60);

        System.out.println("=== hours :: "+ hours);
        System.out.println("=== min   :: "+ ( min < 0 ? ((min-1)+60) : min));
        System.out.println("=== sec   :: "+ ( sec < 0 ? -sec : sec));
        System.out.println("");

    } catch (ParseException e1) {
        e1.printStackTrace();
    }

Upvotes: 0

sudarsan pandey
sudarsan pandey

Reputation: 11

only the format was incorrect... the line

SimpleDateFormat sdf=new SimpleDateFormat("HH:mm a"); 

should be changed to

SimpleDateFormat sdf=new SimpleDateFormat("hh:mm a"); 

everything should be fine after that.

Upvotes: 1

donnyton
donnyton

Reputation: 6054

Since you already have a way to calculate the difference if they are the same AM/PM, you just have to convert them to 24-hour scale:

if(time.isPM())
    //add 12 hours to time

and then do your calculations (assuming they are in the same day). This is also assuming you are not just using the Java Calendar class:

http://download.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html

With Calendar, you can just call

Calendar.getTimeInMillis()

and subtract them from each other.

Upvotes: 1

Arun
Arun

Reputation: 101

You can get date objects for both start & end time. Then get time in millis & subtract.

Difference in Millis = endDate.getTime() - startDate.getTime()

Convert the difference to hours/minutes.

Upvotes: 6

Related Questions