Check date in range java

Check if Date Is Between Two Dates in Java

In this article, we will discuss and dwell on how to compare dates in Java. The problem statement is : Check if a Date is between two dates in Java. This roughly translates to Given a date, we need to check if it lies between the range of two dates. Let us understand this with a sample input example.

We will discuss different solutions to this problem in great depth and detail to make it captivating. Let us first have a quick look at how Dates are represented in Java.

Date & Local Date Class in Java

In Java, we can represent Dates as text in a Stringtype variable. But using a String would make formatting the date for different operations very resilient. So, to avoid this Java provides the Date and LocalDate class to perform operations on a Date meta type easily.

Date Class in Java

It is present in java.util package. We can create a date of any format (DD/MM/YYYYY, MM/DD/YYYY, YYYY/MM/DD, etc.) using the SimpleDateFormat class and instantiate it to a Date class object using the parse() method of the SimpleDateFormat class.

Читайте также:  Recursive directory iterator php

LocalDate class in Java

It is present in java.time package. We can create a date of only a specific format i.e. YYYY-MM-DD. We instantiate the LocalDate object using the of() method and pass the relevant parameters to it.

We can also create a LocalDate object using the parse() method where we need to pass the required Date as a String in the format YYYY-MM-DD.

Let us see the sample code to create custom dates using the classes above. It is important to get an idea as we will look at more examples related to this.

Источник

Java: how do I check if a Date is within a certain range?

So if the Nov 8 is given then its fail if it is Nov 7, 6, 5 and 3, 2, 1 is a Pass since it is within the range.,Mkyong.com is providing Java and Spring tutorials and code snippets since 2008. All published articles are simple and easy to understand and well tested in our development environment.,Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.,how to validate date of birth if i click on it it should not be empty could u tell me how its possible

A Java example to check if a provided date is within a range of 3 momths before and after current date. The idea is quite simple, just use Calendar class to roll the month back and forward to create a “date range”, and use the Date.before() and Date.after() to check if the Date is within the range.

 if (dateToValidate.before(currentDateAfter3Months.getTime()) && dateToValidate.after(currentDateBefore3Months.getTime()))  
 package com.mkyong.date; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DateValidator < public boolean isThisDateWithin3MonthsRange(String dateToValidate, String dateFromat) < SimpleDateFormat sdf = new SimpleDateFormat(dateFromat); sdf.setLenient(false); try < // if not valid, it will throw ParseException Date date = sdf.parse(dateToValidate); // current date after 3 months Calendar currentDateAfter3Months = Calendar.getInstance(); currentDateAfter3Months.add(Calendar.MONTH, 3); // current date before 3 months Calendar currentDateBefore3Months = Calendar.getInstance(); currentDateBefore3Months.add(Calendar.MONTH, -3); /*************** verbose ***********************/ System.out.println("\n\ncurrentDate : " + Calendar.getInstance().getTime()); System.out.println("currentDateAfter3Months : " + currentDateAfter3Months.getTime()); System.out.println("currentDateBefore3Months : " + currentDateBefore3Months.getTime()); System.out.println("dateToValidate : " + dateToValidate); /************************************************/ if (date.before(currentDateAfter3Months.getTime()) && date.after(currentDateBefore3Months.getTime())) < //ok everything is fine, date in range return true; >else < return false; >> catch (ParseException e) < e.printStackTrace(); return false; >> > 

A simple unit test to prove above code is working correctly, if you run below unit test, all he cases will be passed.

 package com.mkyong.test; import org.junit.*; import com.mkyong.date.DateValidator; import static org.junit.Assert.*; public class DateValidatorRangeTest < private DateValidator dateValidator; @Before public void init() < dateValidator = new DateValidator(); >@Test public void testDateWithinRange_1() < assertTrue(dateValidator.isThisDateWithin3MonthsRange("31/01/2012", "dd/MM/yyyy")); >@Test public void testDateWithinRange_2() < assertFalse(dateValidator.isThisDateWithin3MonthsRange("31/01/2011", "dd/MM/yyyy")); >@Test public void testDateWithinRange_3() < assertTrue(dateValidator.isThisDateWithin3MonthsRange("20/02/2012", "dd/MM/yyyy")); >@Test public void testDateWithinRange_4() < assertFalse(dateValidator.isThisDateWithin3MonthsRange("21/05/2012", "dd/MM/yyyy")); >> 

All cases are passed and output following extra info on console.

 currentDate : Mon Feb 20 13:36:59 SGT 2012 currentDateAfter3Months : Sun May 20 13:36:59 SGT 2012 currentDateBefore3Months : Sun Nov 20 13:36:59 SGT 2011 dateToValidate : 31/01/2012 currentDate : Mon Feb 20 13:36:59 SGT 2012 currentDateAfter3Months : Sun May 20 13:36:59 SGT 2012 currentDateBefore3Months : Sun Nov 20 13:36:59 SGT 2011 dateToValidate : 31/01/2011 currentDate : Mon Feb 20 13:36:59 SGT 2012 currentDateAfter3Months : Sun May 20 13:36:59 SGT 2012 currentDateBefore3Months : Sun Nov 20 13:36:59 SGT 2011 dateToValidate : 20/02/2012 currentDate : Mon Feb 20 13:36:59 SGT 2012 currentDateAfter3Months : Sun May 20 13:36:59 SGT 2012 currentDateBefore3Months : Sun Nov 20 13:36:59 SGT 2011 dateToValidate : 21/05/2012 

Answer by Diego Simpson

The LocalDate class represents a date-only value, without time-of-day and without time zone.,your logic would work fine . As u mentioned the dates ur getting from the database are in timestamp , You just need to convert timestamp to date first and then use this logic.,An easy way is to convert the dates into milliseconds after January 1, 1970 (use Date.getTime()) and then compare these values.,Perhaps you want to work with only the date, not the time-of-day.

boolean isWithinRange(Date testDate)

Doesn't seem that awkward to me. Note that I wrote it that way instead of

return testDate.after(startDate) && testDate.before(endDate); 

Answer by Kamryn Fischer

Doesn't seem that awkward to me. Note that I wrote it that way instead of ,Part of the standard Java API with a bundled implementation.,Date.getTime() returns the number of milliseconds since 1/1/1970 00:00:00 GMT, and is a long so it's easily comparable.,so it would work even if testDate was exactly equal to one of the end cases.

boolean isWithinRange(Date testDate)

Doesn't seem that awkward to me. Note that I wrote it that way instead of

return testDate.after(startDate) && testDate.before(endDate); 

tl;dr

ZoneId z = ZoneId.of( "America/Montreal" ); // A date only has meaning within a specific time zone. At any given moment, the date varies around the globe by zone. LocalDate ld = givenJavaUtilDate.toInstant() // Convert from legacy class `Date` to modern class `Instant` using new methods added to old classes. .atZone( z ) // Adjust into the time zone in order to determine date. .toLocalDate(); // Extract date-only value. LocalDate today = LocalDate.now( z ); // Get today’s date for specific time zone. LocalDate kwanzaaStart = today.withMonth( Month.DECEMBER ).withDayOfMonth( 26 ); // Kwanzaa starts on Boxing Day, day after Christmas. LocalDate kwanzaaStop = kwanzaaStart.plusWeeks( 1 ); // Kwanzaa lasts one week. Boolean isDateInKwanzaaThisYear = ( ( ! today.isBefore( kwanzaaStart ) ) // Short way to say "is equal to or is after". && today.isBefore( kwanzaaStop ) // Half-Open span of time, beginning inclusive, ending is *exclusive*. ) 

Convert your java.util.Date objects to Instant objects.

Instant start = myJUDateStart.toInstant(); Instant stop = … 

If getting java.sql.Timestamp objects through JDBC from a database, convert to java.time.Instant in a similar way. A java.sql.Timestamp is already in UTC so no need to worry about time zones.

Instant start = mySqlTimestamp.toInstant() ; Instant stop = … 

Get the current moment for comparison.

Compare using the methods isBefore, isAfter, and equals.

Boolean containsNow = ( ! now.isBefore( start ) ) && ( now.isBefore( stop ) ) ; 

The LocalDate class represents a date-only value, without time-of-day and without time zone.

LocalDate start = LocalDate.of( 2016 , 1 , 1 ) ; LocalDate stop = LocalDate.of( 2016 , 1 , 23 ) ; 

To get the current date, specify a time zone. At any given moment, today’s date varies by time zone. For example, a new day dawns earlier in Paris than in Montréal.

LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) ); 

We can use the isEqual , isBefore , and isAfter methods to compare. In date-time work we commonly use the Half-Open approach where the beginning of a span of time is inclusive while the ending is exclusive.

Boolean containsToday = ( ! today.isBefore( start ) ) && ( today.isBefore( stop ) ) ; 

We can adjust the LocalDate into a specific moment, the first moment of the day, by specifying a time zone to get a ZonedDateTime . From there we can get back to UTC by extracting a Instant .

ZoneId z = ZoneId.of( "America/Montreal" ); Interval interval = Interval.of( start.atStartOfDay( z ).toInstant() , stop.atStartOfDay( z ).toInstant() ); Instant now = Instant.now(); Boolean containsNow = interval.contains( now ); 

That's the correct way. Calendars work the same way. The best I could offer you (based on your example) is this:

boolean isWithinRange(Date testDate) < return testDate.getTime() >= startDate.getTime() && testDate.getTime()

Answer by Ariel Nielsen

$start_date = '2020-10-21'; $end_date = '2020-10-15'; $date_check = '2020-08-28'; if ($this->check_in_range($start_date, $end_date, $date_from_user)) < echo "within range"; >else < echo "not within range"; >function check_in_range($start_date, $end_date, $date_from_user) < // Convert to timestamp $start = strtotime($start_date); $end = strtotime($end_date); $check = strtotime($date_from_user); // Check that user date is between start & end return (($start

Answer by Evie Owen

Given a date list and date range, the task is to write a Python program to check whether any date exists in the list in a given range.,Python program to check whether a number is Prime or not,Similar to the above method, the only difference being any() is used to check for the presence of any date in range.,Python program to check if a string is palindrome or not

Answer by Kye Harrington

In this quick tutorial, we'll learn about several different ways to check if two java.util.Date objects have the same day.,In this quick tutorial, we've explored several ways of checking if two java.util.Date objects contain the same day.,Let's see how we can check if two Date objects have the same day using this class:,Consequently, using this approach, we'll be able to determine if the two Date objects contain the same day.

Let's see how we can check if two Date objects have the same day using this class:

public static boolean isSameDay(Date date1, Date date2)
public static boolean isSameDayUsingInstant(Date date1, Date date2)

Using this, we'll format the Date, convert it to a String object, and then compare them using the standard equals method:

public static boolean isSameDay(Date date1, Date date2)

Firstly, we need to create a Calendar instance and set the Calendar objects' time using each of the provided dates. Then we can query and compare the Year-Month-Day attributes individually to figure out if the Date objects have the same day:

public static boolean isSameDay(Date date1, Date date2)
 org.apache.commons commons-lang3 3.12.0 

Then we can simply use the method isSameDay from DateUtils:

DateUtils.isSameDay(date1, date2);

The artifact can be found on Maven Central:

In this library, org.joda.time.LocalDate represents a date without time. Hence, we can construct the LocalDate objects from the java.util.Date objects and then compare them:

public static boolean isSameDay(Date date1, Date date2)
 com.darwinsys hirondelle-date4j 1.5.1 

Using this library, we need to construct the DateTime object from a java.util.Date object. Then we can simply use the isSameDayAs method:

public static boolean isSameDay(Date date1, Date date2)

Answer by Juliette Castaneda

I have a series of ranges with start dates and end dates. I want to check to see if a date is within that range.,Part of the standard Java API with a bundled implementation.,ADBlock is blocking some content on the site,here m sharing a bit to convert from Timestamp to date.

Date.before() and Date.after() seem to be a little awkward to use. What I really need is something like this pseudocode:

boolean isWithinRange(Date testDate) < return testDate >= startDate && testDate

Источник

Как проверить, находится ли Date в определенном диапазоне в Java?

Как проверить, находится ли Date в определенном диапазоне в Java?

Пример Java, чтобы проверить, находится ли предоставленная дата в диапазоне 3 месяцев до и после текущей даты. Идея довольно проста, просто используйте классCalendar для отката месяца назад и вперед, чтобы создать «диапазон дат», и используйте Date.before() и Date.after() , чтобы проверить, находится ли дата в пределах диапазон.

if (dateToValidate.before(currentDateAfter3Months.getTime()) && dateToValidate.after(currentDateBefore3Months.getTime())) 
package com.example.date; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DateValidator < public boolean isThisDateWithin3MonthsRange(String dateToValidate, String dateFromat) < SimpleDateFormat sdf = new SimpleDateFormat(dateFromat); sdf.setLenient(false); try < // if not valid, it will throw ParseException Date date = sdf.parse(dateToValidate); // current date after 3 months Calendar currentDateAfter3Months = Calendar.getInstance(); currentDateAfter3Months.add(Calendar.MONTH, 3); // current date before 3 months Calendar currentDateBefore3Months = Calendar.getInstance(); currentDateBefore3Months.add(Calendar.MONTH, -3); /*************** verbose ***********************/ System.out.println("\n\ncurrentDate : " + Calendar.getInstance().getTime()); System.out.println("currentDateAfter3Months : " + currentDateAfter3Months.getTime()); System.out.println("currentDateBefore3Months : " + currentDateBefore3Months.getTime()); System.out.println("dateToValidate : " + dateToValidate); /************************************************/ if (date.before(currentDateAfter3Months.getTime()) && date.after(currentDateBefore3Months.getTime())) < //ok everything is fine, date in range return true; >else < return false; >> catch (ParseException e) < e.printStackTrace(); return false; >> >

Простой модульный тест для проверки приведенного выше кода работает правильно, если вы запустите ниже модульный тест, все случаи будут пройдены.

package com.example.test; import org.junit.*; import com.example.date.DateValidator; import static org.junit.Assert.*; public class DateValidatorRangeTest < private DateValidator dateValidator; @Before public void init() < dateValidator = new DateValidator(); >@Test public void testDateWithinRange_1() < assertTrue(dateValidator.isThisDateWithin3MonthsRange("31/01/2012", "dd/MM/yyyy")); >@Test public void testDateWithinRange_2() < assertFalse(dateValidator.isThisDateWithin3MonthsRange("31/01/2011", "dd/MM/yyyy")); >@Test public void testDateWithinRange_3() < assertTrue(dateValidator.isThisDateWithin3MonthsRange("20/02/2012", "dd/MM/yyyy")); >@Test public void testDateWithinRange_4() < assertFalse(dateValidator.isThisDateWithin3MonthsRange("21/05/2012", "dd/MM/yyyy")); >>

Все случаи передаются и выводятся после дополнительной информации на консоли.

currentDate : Mon Feb 20 13:36:59 SGT 2012 currentDateAfter3Months : Sun May 20 13:36:59 SGT 2012 currentDateBefore3Months : Sun Nov 20 13:36:59 SGT 2011 dateToValidate : 31/01/2012 currentDate : Mon Feb 20 13:36:59 SGT 2012 currentDateAfter3Months : Sun May 20 13:36:59 SGT 2012 currentDateBefore3Months : Sun Nov 20 13:36:59 SGT 2011 dateToValidate : 31/01/2011 currentDate : Mon Feb 20 13:36:59 SGT 2012 currentDateAfter3Months : Sun May 20 13:36:59 SGT 2012 currentDateBefore3Months : Sun Nov 20 13:36:59 SGT 2011 dateToValidate : 20/02/2012 currentDate : Mon Feb 20 13:36:59 SGT 2012 currentDateAfter3Months : Sun May 20 13:36:59 SGT 2012 currentDateBefore3Months : Sun Nov 20 13:36:59 SGT 2011 dateToValidate : 21/05/2012

Источник

Оцените статью