1

I'm trying to get the time differente between two Time vars like this

long timeDiffLong = hFim.getTime() - hInic.getTime();
Time timeDiff = new Time(timeDiffLong);

The output is comming something like this

hFim = 17:30:00
hInic = 17:00:00
timeDiff = 20:30:00

instead of just showing 00:30:00 i always get 20h plus the result

  • What's the value of `timeDiffLong` in this case, and how are you constructing `hFim` and `hInic`? A [mcve] here would make it easier to help you. – Jon Skeet Oct 13 '16 at 11:50
  • Possible duplicate of [How to calculate the difference between two java.sql.Time values?](http://stackoverflow.com/questions/25847798/how-to-calculate-the-difference-between-two-java-sql-time-values) – Unknown Oct 13 '16 at 11:51

4 Answers4

3

If you use Java 8, you can do:

LocalTime from = hFim.toLocalTime();
LocalTime to = hInic.toLocalTime();

Duration d = Duration.between(from, to);

You can then query the hour/minute etc. with e.g. d.toMinutes().

assylias
  • 321,522
  • 82
  • 660
  • 783
2

By doing this

 Time timeDiff = new Time(timeDiffLong);

you create a new time object, with timeDiffLong being the milliseconds since 1970-01-01 00:00 UTC. Since the difference is 30 minutes, the Time object will refer to 1970-01-01 00:30 UTC. But here comes the catch: timeDiff.toString() will output the time in the default time zone, that is, in most cases the time zone where you are currently are.

Long story short: Do not force an interval (duration, time difference) into a Time object. Either use a Duration class (Joda has one) or just do the division and modulo calculations yourself, as proposed by Kushan.

Erich Kitzmueller
  • 36,381
  • 5
  • 80
  • 102
0

Looks like a duplicated question, have you seen already this answer?

How to find difference between two Joda-Time DateTimes in minutes

You should take a look at Joda time:

http://www.joda.org/joda-time/

Community
  • 1
  • 1
0

Your problem is that when you create the time diff with

Time timeDiff = new Time(timeDiffLong);

and output that with System.out.println(timeDiff) then the result is shown for your local time zone. You can see that when you do this:

System.out.println(new Time(0));
TimeZone.setDefault(TimeZone.getTimeZone("PST"));
System.out.println(new Time(0));

That produces the following output here

00:00:00 //will probably be 20:00:00 for you
16:00:00

In short: Your time difference is shown as a GMT date converted to your local time zone and that is why its several hours off.

Florian Link
  • 638
  • 4
  • 11