Get hour from date() in java [duplicate]

90
January 17, 2019, at 06:40 AM

This question already has an answer here:

  • Java: getMinutes and getHours 10 answers
  • Display and save only hours in int 2 answers

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

Answer 1

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

Answer 2

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;
}
READ ALSO
Modified N Queens with placed queen

Modified N Queens with placed queen

So, I'm creating an N Queens problem solver with BacktrackingThe twist however is that the first queen is placed by the user and then the backtracking is ran to process the other 7 queens

102
Need help in extracting a expression from a log using regular expressions in Java

Need help in extracting a expression from a log using regular expressions in Java

I have a log as a string, and I am trying to capture the error message from itthe regex I tried did not work

108
How to find the fitness of Sudoku in java [on hold]

How to find the fitness of Sudoku in java [on hold]

Suppose this is the matrixI want fitness of this matrix for solving Sudoku

89
Get InputStream and JSON in RestTemplate Response with postForObject

Get InputStream and JSON in RestTemplate Response with postForObject

I currently have a RestTemplate Response Object with String fields to get the Response dataI want to send InputStream in the same Object

88