-1

for comparison hours I need to get them out Date(). I have two dates I need to find the difference in them exactly in the hours

Date date1 = new Date();
Date date2 = new Date();
System.out.println(date1.getHours()-date2.getHours());

I understand it is not correct code, but need something like that

Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108
  • 3
    You should be using the `java.time` APIs instead, `Date` is effectively deprecated and "mathematical" manipulation of time is the worst thing you can do - what happens if those times cross a daylight savings boundary? Something like `Duration.between(fromdate, todate).toHours();`, where `fromdate` and `todate` are `Instant` would be better – MadProgrammer Jan 15 '19 at 22:44
  • 1
    FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Jan 15 '19 at 22:52

2 Answers2

3

Mathematical manipulation of date/times values is ignorant and possibly the worst thing you can do. There are a lot of rules which surround date/time manipulation, which is best left to a decent and well tested API.

Since Java 8, you should be using the java.time API or it's backport for earlier versions.

For example...

Instant now = Instant.now();
Instant then = now.minus(2, ChronoUnit.DAYS);

System.out.println(Duration.between(then, now).toHours());

which prints 48

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

Get the seconds difference, and then just convert seconds to hours.

var startDate = new Date();
var endDate = new Date();
var seconds = (endDate.getTime() - startDate.getTime()) / 1000;
// 3.557 seconds difference between the two times
var hourDiff = seconds / 60 / 60;
// 0.0009880555555555556 hours..

Wrapped into function:

function getHourDiff(date1, date2) {
    var seconds = (date1.getTime() - date2.getTime()) / 1000;
    return seconds / 60 / 60;
}
  • 1
    FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Jan 15 '19 at 22:52