Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Date & Time of Day

Tags:

java

date

I have an application that passes in java.util.Date. I want to check whether this date is within a specified time of day (e.g. between 10:30 & 11:30), I don't care about the date, just the time of day.

Can anyone show me a simple way to do this?

Thanks

like image 384
Gaz Avatar asked Apr 24 '26 11:04

Gaz


1 Answers

This is what the Calendar class is for. Assuming date is your Date object:

Calendar cal = Calendar.getInstance();
cal.setTime(date);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minutes = cal.get(Calendar.MINUTE);
if (hour == 10 && minutes >= 30 || hour == 11 && minutes <= 30) {
   ... 
}
like image 88
cletus Avatar answered Apr 26 '26 02:04

cletus