1

I have two times in String format. 9:00 AM and 10:00 AM. I want to subtract them. the difference must be 1 hour. I tried the following code to do that but i am not getting the desired results:

String time1 = "9:00 AM";
String time2 = "10:00 AM";
SimpleDateFormat formatter = new SimpleDateFormat("h:mm a");
Date d1 = formatter.parse(time1);
Date d2 = formatter.parse(time2);
long timeDiff = d2.getTime() - d1.getTime();
Date diff = new Date(timeDiff);
System.out.println(formatter.format(diff));

How can i do that ?

Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60
Usman Riaz
  • 2,920
  • 10
  • 43
  • 66
  • of courser the questioner is expecting the difference as the output – Rajesh Apr 02 '15 at 10:53
  • Possible duplicate of http://stackoverflow.com/questions/5351483/calculate-date-time-difference-in-java. – pepuch Apr 02 '15 at 10:53
  • You could use until method of Temporal interface from new datetime API. – mkrakhin Apr 02 '15 at 10:55
  • @singhakash That's because he is incorrectly converting the diff (3600000 milliseconds) into a Date. This will result in the date 3600000 milliseconds since epoch (1970-01-01 00:00), of which he is just showing the "h:mm a" part. – Adriaan Koster Apr 02 '15 at 10:58

4 Answers4

3

Try something like:

long timeDiff = d2.getTime() - d1.getTime();
System.out.println((timeDiff / 3600000) + " hour/s " + (timeDiff % 3600000) / 60000 + " minutes");
Output
1 hour/s 5 minutes
SMA
  • 36,381
  • 8
  • 49
  • 73
3

Use Joda time! See this question

DateTimeFormatter formatter = DateTimeFormat.forPattern("H:mm a");
DateTime time1 = formatter.parseDateTime("9:00 AM");
DateTime time2 = formatter.parseDateTime("10:00 AM");

Duration duration = new Duration(time1, time2);
System.out.printf("%s hour(s), %s minute(s)%n", duration.getStandardHours(), duration.getStandardMinutes());
Community
  • 1
  • 1
Adriaan Koster
  • 15,870
  • 5
  • 45
  • 60
  • 1
    Or if on Java 8, use the improved built-in [date-time API](http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html) which has been designed based on Joda. – Mick Mnemonic Apr 02 '15 at 11:23
1

Your approach seems to be correct. Only thing you should not do is, changing timeDiff to new Date. Rather, change it to get time in minutes and hours as follows Ex : -

long diffMinutes = timeDiff / (60 * 1000) % 60;
long diffHours = timeDiff / (60 * 60 * 1000) % 24;
System.out.println(diffHours+" hours "+ diffMinutes +" minutes");

here is the complete code You can refer to if you want more proper display of time difference,

import java.util.*;
import java.lang.*;
import java.io.*;
import java.text.*;

/* Name of the class has to be "Main" only if the class is public. */

class TimeDiffTester
{
    public static String show(long value, String showAs) {
        if(value == 0) {
            return "";
        } else {
            return Math.abs(value) +" "+showAs+" ";
        }
    }
    public static void getDifferenceInTime(String time1, String time2) throws java.lang.Exception {
        SimpleDateFormat formatter = new SimpleDateFormat("h:mm a");
        Date d1 = formatter.parse(time1);
        Date d2 = formatter.parse(time2);
        long timeDiff = d2.getTime() - d1.getTime();

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

        String difference = show(diffDays, "days") + show(diffHours, "hours") + show(diffMinutes, "minutes") + show(diffSeconds, "seconds");
        if(diffDays < 0 || diffHours < 0 || diffMinutes < 0 || diffSeconds < 0) {
            System.out.println("-"+difference); 
        } else {
            System.out.println("+"+difference); 
        }
    }
    public static void main (String[] args) throws java.lang.Exception
    {
            String time1 = "4:30 PM";
            String time2 = "5:00 PM";

            getDifferenceInTime(time1,time2);

    }
}
Nielarshi
  • 1,126
  • 7
  • 11
0

Here is best example given.

1000 milliseconds = 1 second
60 seconds = 1 minute
60 minutes = 1 hour
24 hours = 1 day


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

    }

Please find reference link for this example

http://www.mkyong.com/java/how-to-calculate-date-time-difference-in-java/

Pratik
  • 944
  • 4
  • 20