0

I have two hh:mm strings, and I want to make comparisons between them.

I mean, I would want to add or subtract them, make operations. I have a string with the current time and another string that says, for example, "15:00". I want to know how many minutes there are between both strings, result that I can take by doing a subtraction. Is that possible?

Seba Paz
  • 55
  • 3
  • 9
  • 2
    Yes it is possible. However there are many resources on the net which can help you with this. SO is a Q & A site. No a tutorial request. Sorry if im being rude but its the truth – MarsOne Sep 03 '13 at 13:56
  • Read about [Date](http://docs.oracle.com/javase/6/docs/api/java/util/Date.html) and [SimpleDateFormat](http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html) – rocketboy Sep 03 '13 at 13:57
  • Convert to minutes and then you can easily add/substract/compare – NeplatnyUdaj Sep 03 '13 at 14:01

3 Answers3

3

You can parse it by using SimpleDateFormat, then use the getTime() method from Date class to obtain the difference in milliseconds.

DateFormat f = new SimpleDateFormat("hh:mm");
Date d1 = f.parse(s1);
Date d2 = f.parse(s2);
long difference = d1.getTime() - d2.getTime(); // milliseconds
Mauren
  • 1,955
  • 2
  • 18
  • 28
0

This will get you started.. Do the following for the two strings & then do the necessary comparisions/add/subtract

String time1 = "15:00";
String time2 = "16:00";

DateFormat sdf = new SimpleDateFormat("hh:mm");
Date date1 = sdf.parse(time1);
Date date2 = sdf.parse(time2);

long milliSecondsDiff = date1.getTime() - date2.getTime(); //in milliseconds
int seconds = milliSecondsDiff/1000; //seconds
int minutes = seconds/60; //minutes
Venkata Krishna
  • 14,926
  • 5
  • 42
  • 56
0

You could use joda datetime for this:

public static void main(String[] args) {

    DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm");
    DateTime first = formatter.parseDateTime("15:00");
    DateTime second = formatter.parseDateTime("15:49");

    Interval interval = new Interval(first, second);
    System.err.println(interval.toDuration().getStandardMinutes());
}

Have a look here

Using Duration also gives you some other neat methods like getStandardSeconds() which would give you 2940 for this case.

u6f6o
  • 2,050
  • 3
  • 29
  • 54