Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell if a date is before a certain time in Java?

Tags:

java

For example given a java.util.Date how could I test if the time was before 12.30 PM that day?

like image 851
deltanovember Avatar asked Aug 18 '11 07:08

deltanovember


People also ask

How do you check if a date is before in Java?

public boolean before(Date dt) The before() method is used to check if a given date is before another given date. Return Value: true if and only if the instant of time represented by this Date object is strictly earlier than the instant represented by when; false otherwise.

How do I check if a date is within a certain range in Java?

We can use the simple isBefore , isAfter and isEqual to check if a date is within a certain date range; for example, the below program check if a LocalDate is within the January of 2020. startDate : 2020-01-01 endDate : 2020-01-31 testDate : 2020-01-01 testDate is within the date range.

How do you check if a date is later than another in Java?

In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.

Can we get timezone from date Java?

DateFormat getTimeZone() Method in Java with ExamplesThe getTimeZone() method in DateFormat class is used to return the current time-zone of the calendar of this DateFormat. Parameters: The method does not take any parameters. Return Value: The method returns timezone associated with the calendar of DateFormat.


2 Answers

Have a look at Calendar.before() Method.

Calendar now = Calendar.getInstance();
now.set(Calendar.HOUR_OF_DAY, 12);
now.set(Calendar.MINUTE, 30);
Calendar givenDate = Calendar.getInstance();
givenDate.setTime(yourDate);

boolean isBefore = now.before(givenDate);
like image 149
flash Avatar answered Oct 10 '22 11:10

flash


This works. It does the check using only the hour and minute portions of your date:

Date yourDate;
Calendar calendar = Calendar.getInstance();
calendar.setTime(yourDate);
boolean before = calendar.get(Calendar.HOUR) * 60 + calendar.get(Calendar.MINUTE) < 12 * 60 + 30;
like image 32
Bohemian Avatar answered Oct 10 '22 13:10

Bohemian