Reputation: 655
I am a newbie in java. I have written this function to find the time difference in hours from the current time to the time in function parameters. The results are kind of mixed, how I can I improve it? Thanks.
private int getTimeDiffFromCurrent(String date, String time)
{
String str_date_time = date + " " + time;
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.getDefault());
try {
Date date_time = (Date) formatter.parse(str_date_time);
int hr = (int)((System.currentTimeMillis() - date_time.getTime())/(1000 * 60 * 60));
return hr>=0? hr : 1000;
}
catch (Exception e) {
System.out.println(e.toString() + ", " + str_date_time);
}
return 1000;
}
Example of used case:
getTimeDiffFromCurrent("19/07/2020", "07:19:00");
Upvotes: 0
Views: 115
Reputation: 22977
If you use the Java Date and Time API available in the java.time
package, then it'll becomes much simpler.
static long getDifferenceInHours(ZonedDateTime dateTime) {
ZonedDateTime now = ZonedDateTime.now();
return Duration
.between(dateTime, now)
.toHours();
}
You can then call it like this:
ZonedDateTime zdt = ZonedDateTime.of(2020, 7, 16, 0, 0, 0, 0, ZoneId.systemDefault());
long difference = getDifferenceInHours(zdt);
System.out.println(difference);
You shouldn't apply math to calculate date and time differences; there are many APIs out there doing the job pretty well.
I used ZonedDateTime
in the abovementioned code, because this takes possible DST changes into consideration. For example, in the Europe/Amsterdam timezone, between 29th March 2020, 00:00 and 05:00 are just 4 hours (instead of 5) due to the wall clock skipping an hour at two.
Upvotes: 3