Check if the time is within the min and max range - java

I don't know what's happening here: I need to return true if the current time is between a given range, ex: now is 15:45:00 and is between 12:00:00(min) and 18:00:00(max), but this method is doing it wrong:
private boolean verifyIfInside(String max, String min){
try {
DateFormat dateFormat = new SimpleDateFormat ("HH:mm:ss");
Date date = new Date();
String hour1 = min;
String hour2 = max;
String newHour = dateFormat.format(date);
Date minHour, maxHour, nowHour;
minHour = dateFormat.parse(hora1);
maxHour = dateFormat.parse(hora2);
nowHour = dateFormat.parse(newHour );
if ((minHour.compareTo(nowHour) <= 0) && (maxHour.compareTo(nowHour) >= 0)){
return true;
} else {
return false;
}
} catch (ParseException parseException){
parseException.printStackTrace();
return false;
}
}

I have tested it with .before() and .after() Its working fine and you can also reduce the code like:-
private static boolean verifyIfInside(String min , String max){
try {
DateFormat dateFormat = new SimpleDateFormat ("HH:mm:ss");
String current_time = dateFormat.format(new Date());
Date minHour = dateFormat.parse(min);
Date maxHour = dateFormat.parse(max);
Date curr_time = dateFormat.parse(current_time);
return minHour.before(curr_time) && maxHour.after(curr_time);
} catch (ParseException parseException){
parseException.printStackTrace();
return false;
}
}

Time zone is crucial. Your verification makes no sense unless you know in which time zone you want the current time. For the reader’s sake, also specify it in your code.
The date and time classes you use, Date, DateFormat and SimpleDateFormat, are not only long outdated, the last one in particular is also renowned for being troublesome to work with. Instead I recommend you use java.time, the modern Java date and time API. This even furnishes a LocalTime class, a time of day without a date, which matches your need much more precisely than Date.
So your method is written clearly and tersely thus:
private static boolean verifyIfInside(String max, String min) {
LocalTime now = LocalTime.now(ZoneId.of("Europe/Budapest"));
LocalTime minHour = LocalTime.parse(min);
LocalTime maxHour = LocalTime.parse(max);
return ! (now.isBefore(minHour) || now.isAfter(maxHour));
}
Please substitute your desired time zone if it didn’t happen to be Europe/Budapest.
Since I understood that you wanted your range to be inclusive, and since isBefore and isAfter mean strictly before and after, I used a negation to test that the time is “not outside the range”.
I am furthermore exploiting the fact that your time format, 12:00:00, agrees with ISO 8601, the format that the modern classes parse as their default, that is, without any explicit formatter. A potential downside is that validation of the time strings is weaker: parse() will also accept 12:00 and 12:23:29.82376342. If you need to reject these as errors, you do need an explicit formatter.
What went wrong in your code?
As far as I can tell, your code in the question is working correctly (if we just change hora1 to hour1 or the other way around, and hora2 too). You may have been confused about the order of the arguments. The following returns true if run between 12 and 18: verifyIfInside("18:00:00", "12:00:00"). However, many would find it natural to write the call as verifyIfInside("12:00:00", "18:00:00"), which returns false always. So it would almost surely be better to declare the method as verifyIfInside(String min, String max), that is, with min before max.
Another possibility is, of course, as I mentioned, that your JVM is using a different time zone from the one you think it is using. This would very likely give you unexpected results. The only way to be sure this is not the case is to specify explicitly which time zone it should use.

It works correctly with the suggested modifications:
Reverse the min and max parameters.
Use .before() and .after() to compare if the current hour is after min hour and before max hour.
To include the min/max time boundaries you can use: !nowHour.after(maxHour) && !nowHour.before(minHour);
To exclude the min/max time boundaries use this instead: nowHour.after(minHour) && nowHour.before(maxHour);
If you are constrained to an older version of java, consider using the appropriate java.time ThreeTen-Backport project as #Basil Bourque suggested. Otherwise, use the latest time API in Java 8+.
code:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class scratch_21 {
public static void main(String[] args) {
System.out.println(verifyIfInside("14:00:00", "14:15:00"));
}
private static boolean verifyIfInside(String min, String max) {
try {
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
Date date = new Date();
String hora1 = min;
String hora2 = max;
String newHour = dateFormat.format(date);
Date minHour, maxHour, nowHour;
minHour = dateFormat.parse(hora1);
maxHour = dateFormat.parse(hora2);
nowHour = dateFormat.parse(newHour);
return nowHour.after(minHour) && nowHour.before(maxHour);
} catch (ParseException parseException) {
parseException.printStackTrace();
return false;
}
}
}

Related

Date Difference Calculation in Java by excluding weekends [duplicate]

This question already has answers here:
Calculate number of weekdays between two dates in Java
(20 answers)
Closed 1 year ago.
Am very beginner and new to Java platform. I have the below 3 simple Java date difference calculation functions. I wanted to exclude weekends on the below calculations in all the 3 methods. Can anyone please help how to exclude weekends for the below dateDiff calculations?
public static String getDatesDiff(String date1, String date2) {
String timeDiff = "";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(date1);
d2 = format.parse(date2);
long diff = d2.getTime() - d1.getTime();
timeDiff = ""+diff;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return timeDiff;
}
public static String getDatesDiffAsDays(String date1, String date2) {
String timeDiff = "";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(date1);
d2 = format.parse(date2);
long diff = d2.getTime() - d1.getTime();
String days = ""+(diff / (24 * 60 * 60 * 1000));
timeDiff = days;
timeDiff = timeDiff.replaceAll("-", "");
timeDiff = timeDiff+" days";
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return timeDiff;
}
public static String getDatesDiffAsDate(String date1, String date2) {
String timeDiff = "";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(date1);
d2 = format.parse(date2);
long diff = d2.getTime() - d1.getTime();
String days = (diff / (24 * 60 * 60 * 1000))+" days";
String hours = (diff / (60 * 60 * 1000) % 24)+"h";
String minutes = (diff / 1000 % 60)+"mts";
String seconds = (diff / (60 * 1000) % 60)+"sec";
timeDiff = days;
timeDiff = timeDiff.replaceAll("-", "");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return timeDiff;
}
This code is fundamentally broken. java.util.Date doesn't represent a date, it represents a timestamp. But if you're working with moments in time, you have a problem: not all days are exactly 24 hours long. For example, daylight savings exists, making some days 25 or 23 hours. At specific moments in time in specific places on the planet, entire days were skipped, such as when a place switches which side of the international date line it is on, or when Russia was the last to switch from Julian to Gregorian (the famed October Revolution? Yeah, that happened in November actually!)
Use LocalDate which represents an actual date, not a timestamp. Do not use Date, or SimpleDateFormat – these are outdated and mostly broken takes on dates and times. The java.time package is properly thought through.
When is 'the weekend'? In some places, Friday and Saturday are considered the weekend, not Saturday and Sunday.
If you're excluding weekends, presumably you'd also want to exclude mandated holidays. Many countries state that Jan 1st, regardless of what day that is, counts as a Sunday, e.g. for the purposes of government buildings and services being open or not.
Lessons you need to take away from this:
Dates are incredibly complicated, and as a consequence, are a horrible idea for teaching basic principles.
Do not use java.util.Date, Calendar, GregorianCalendar, or SimpleDateFormat, ever. Use the stuff in java.time instead.
If you're writing math like this, you're probably doing it wrong – e.g. ChronoUnit.DAYS.between(date1, date2) does all that math for you.
You should probably just start at start date, and start looping: check if that date counts as a working day or not (and if it is, increment a counter), then go to the next day. Keep going until the day is equal to the end date, and then return that counter. Yes, this is 'slow', but a computer will happily knock through 2 million days (that covers over 5000 years worth) in a heartbeat for you. The advantage is that you can calculate whether or not a day counts as a 'working day' (which can get incredibly complicated. For example, most mainland European countries and I think the US too mandates that Easter is a public holiday. Go look up and how to know when Easter is. Make some coffee first, though).
If you really insist on going formulaic and defining weekends as Saturday and Sunday, it's better to separately calculate how many full weeks are between the two dates and multiply that by 5, and then add separately the half-week 'on the front of the range' and the half-week at the back. This will be fast even if you ask for a hypothetical range of a million years.
That is not how you handle exceptions. Add throws X if you don't want to deal with it right now, or, put throw new RuntimeException("unhandled", e); in your catch blocks. Not this, this is horrible. It logs half of the error and does blindly keeps going, with invalid state.
Almost all interesting questions, such as 'is this date a holiday?' are not answerable without knowing which culture/locale you're in. This includes seemingly obvious constants such as 'is Saturday a weekend day?'.
rzwitserloot has already brought up many valid points about problems in your code.
This is an example of how you could count the working days:
LocalDate startDate = ...;
LocalDate endDateExclusive = ...;
long days = startDate.datesUntil(endDateExclusive)
.filter(date -> isWorkingDay(date))
.count();
And, of course, you need to implement the isWorkingDay method. An example would be this:
public static boolean isWorkingDay(LocalDate date) {
DayOfWeek dow = date.getDayOfWeek();
return (dow != DayOfWeek.SATURDAY && dow != DayOfWeek.SUNDAY);
}
I used LocalDate to illustrate the example. LocalDate fits well if you are working with concepts like weekend days and holidays. However, if you want to also include the time component, then you should also take clock adjustments like DST into account; otherwise a "difference" does not make sense.
I assume the user to input an object representing some datetime value, not a String. The parsing of a string does not belong to this method, but should be handled elsewhere.
Already been said, but I repeat: don't use Date, Calendar and SimpleDateFormat. They're troublesome. Here are some reasons why.
If you want to take the time into consideration, it'll get a little more complex. For instance, ChronoUnit.DAYS.between(date1, date2) only supports a single, contiguous timespan. Gaps in the timespan, like excluding certain periods of time, is not. Then you have to walk over each date and get the associated duration of that portion of date.
First, we could create a LocalTimeRange class, which represents a time span at a certain day.
public record LocalTimeRange(LocalTime start, LocalTime endExclusive) {
public static final LocalTimeRange EMPTY = new LocalTimeRange(null, null);
public Duration toDuration(LocalDate date, ZoneId zone) {
if (this.equals(EMPTY)) {
return Duration.ZERO;
}
var s = ZonedDateTime.of(date, Objects.requireNonNullElse(start, LocalTime.MIN), zone);
var e = (endExclusive != null ? ZonedDateTime.of(date, endExclusive, zone) : ZonedDateTime.of(date.plusDays(1), LocalTime.MIN, zone));
return Duration.between(s, e);
}
}
Calculations are not done immediately, because the duration in between the two wall clock times, depends on the date and timezone. The toDuration method calculates this.
Then we'll create a method which defines what times on each day are counted as a non-weekend day. In this example, I have defined a weekend to be from Friday, 12:00 (noon) until Sunday, 23:59 (midnight).
private static Duration nonWeekendHours(LocalDate date, ZoneId zone) {
var result = switch (date.getDayOfWeek()) {
case MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY -> new LocalTimeRange(LocalTime.MIDNIGHT, null);
case FRIDAY -> new LocalTimeRange(LocalTime.MIDNIGHT, LocalTime.NOON);
case SATURDAY,
SUNDAY -> new LocalTimeRange(null, null);
};
return result.toDuration(date, zone);
}
The LocalTimeRange::toDuration method is called with the passed LocalDate and ZoneId arguments.
Note that passing null as LocalTimeRange's second argument means 'until the end of the day'.
At last we could stream over all dates of a certain period and calculate how much time are the non-weekend hours for each day, and then reduce them to get the total amount of time:
LocalDate startDate = ...;
LocalDate endDate = ...;
ZoneId zone = ...;
Duration result = startDate.datesUntil(endDate)
.map(date -> nonWeekendHours(date, zone))
.reduce(Duration.ZERO, Duration::plus);
With the retrieved Duration instance, you can easily get the time parts with the get<unit>Part() methods,
Online demo

Date.getYear() vs. Calendar.get(Calendar.YEAR) - change of implementation. Will it work?

I am asking this question cause actually I have absolutely no way to test this case, and maybe someone could explain it to me :)
I have been working on a piece of code that was written by a person who is very new to programming. This code looks like this:
List<Date> dateList = infoFacade.getDateFrom(documentId);
for(Date from : dateList) {
LocalDate now1 = LocalDate.now();
int year = now1.getYear();
int previousyear = now1.getYear()-1;
int yearfrom = from.getYear()+1900;
if((yearfrom == year )|| (yearfrom == previousyear )){
idoc.setBauinfoArzvon(from);
}
}
I have rewritten it a little bit, so we stop using a deprecated method. It looks like this:
for (Date from : infoFacade.getDateFrom(documentId))
{
cal.setTime(from);
int yearfrom = cal.get(Calendar.YEAR);
if ((yearfrom == LocalDate.now().getYear())
|| (yearfrom == (LocalDate.now().getYear() - 1)))
{
idoc.setDateFrom(from);
}
}
I am worried about all that +1900 or -1900 thing. Should I add or substract something from the yearfrom variable to get the same results as in the code before refactoring?
Assuming you cannot change the return type of infoFacade.getDateFrom() my suggestion would be:
ZoneId zone = ZoneId.systemDefault();
LocalDate now1 = LocalDate.now(zone);
int year = now1.getYear();
int previousYear = year - 1;
List<Date> dateList = infoFacade.getDateFrom(documentId);
for (Date from : dateList) {
int yearfrom = from.toInstant().atZone(zone).getYear();
if (yearfrom == year || yearfrom == previousYear) {
idoc.setBauinfoArzvon(from);
}
}
Both versions of your code implicitly rely on the JVM’s time zone (which is fragile). I have made this dependency explicit. I am reading the default time zone and the current date only once to ensure consistent results. And by converting the Date first to an Instant and then to ZonedDateTime I am avoiding both the deprecated method and the old and outdated Calendar class. And any considerations about whether to add or subtract 1900 or not, which gives clearer code and fewer doubts on the part of the reader.
To answer your question more directly too: No, in your rewritten version of the code you should neither add nor subtract 1900 (or any other number). The code does give the same result. This is because Date uses a “1900-based year” (where 2018 is given as 118, for example), while the also outdated Calendar class numbers the years the same way humans do. My worry is different: If either the default time zone changes while the code is running or (unlikely, but possible) New Year passes, LocalDate.now() will not give the same result each time, so your results will be inconsistent. The JVM’s default time zone can be changed at any time from another part of your program or another program running in the same JVM.
I have written a simple test:
public static void main(String[] args) {
Date date = new GregorianCalendar().getTime();
Calendar cal = new GregorianCalendar();
cal.setTime(date);
System.out.println(cal.get(Calendar.YEAR));
System.out.println((LocalDate.now().getYear() - 1));
System.out.println(LocalDate.now().getYear());
LocalDate now1 = LocalDate.now();
int year = now1.getYear();
int previousyear = now1.getYear()-1;
int yearfrom = date.getYear()+1900;
System.out.println(year);
System.out.println(previousyear);
System.out.println(yearfrom);
}
The output of this test is:
2018
2017
2018
2018
2017
2018
So both code samples are giving the same result.
BUT i will try to use the #Ole V.V. answer tomorrow to see what will happen.

What is the proper way to remove the time part from java.util.Date? [duplicate]

This question already has answers here:
Java Date cut off time information
(20 answers)
Closed 8 years ago.
I want to implement a thread-safe function to remove the time part from java.util.Date.
I tried this way
private static final DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
public static Date removeTimeFromDate(Date date) {
Date returnDate = date;
if (date == null) {
return returnDate;
}
//just have the date remove the time
String targetDateStr = df.format(date);
try {
returnDate = df.parse(targetDateStr);
} catch (ParseException e) {
}
return returnDate;
}
and use synchronized or threadLocal to make it thread-safe.
But it there any better way to implement it in Java. It seems this way is a bit verbose.
I am not satisfied with it.
A Date object holds a variable wich represents the time as the number of milliseconds since epoch. So, you can't "remove" the time part. What you can do is set the time of that day to zero, which means it will be 00:00:00 000 of that day. This is done by using a GregorianCalendar:
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(date);
gc.set(Calendar.HOUR_OF_DAY, 0);
gc.set(Calendar.MINUTE, 0);
gc.set(Calendar.SECOND, 0);
gc.set(Calendar.MILLISECOND, 0);
Date returnDate = gc.getTime();
A Date holds an instant in time - that means it doesn't unambiguously specify a particular date. So you need to specify a time zone as well, in order to work out what date something falls on. You then need to work out how you want to represent the result - as a Date with a value of "midnight on that date in UTC" for example?
You should also note that midnight itself doesn't occur on all days in all time zones, due to DST transitions which can occur at midnight. (Brazil is a common example of this.)
Unless you're really wedded to Date and Calendar, I'd recommend that you start using Joda Time instead, as that allows you to have a value of type LocalDate which gets rid of most of these problems.

high performance function for date arithmetic

I need to write the high performance function which calculates the new datetime based on given datetime and timeshift. It accept 2 arguments:
String, representing the date in format YYYYMMDDHHmm
Integer, representing the timeshift in hours
Function returns the string in format of 1st argument which is composed as result of applying the timeshift to 1st argument
It is known in advance that the first argument is always the same during the program lifetime.
My implementation has the following steps:
parsing 1st argument to extract the year,month,date, hours,min
creating GregorianCalendar(year, month, date, hours, min) object
applying method GregorianCalendar.add(HOUR,timeshift)
applying SimpleDateFormat to convert result back into string
Issue is that I do not take advantage from the fact that 1st argument is always the same.
If I will create a class member GregorianCalendar(year, month, date, hours, min), then after the 1st call to my function this object will be modified, which is not good, because I cannot reuse it for the following calls.
If you can, use the Joda-Time library, which makes date arithmetic very simple:
DateTime dt = new DateTime();
DateTime twoHoursLater = dt.plusHours(2);
They have a DateTimeFormatter class that you'd use to do the parsing of your input date-time string into a DateTime, eg:
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyyMMddHHmm");
DateTime dt = fmt.parseDateTime(myDateString);
DateTime result = dt.plusHours(myTimeshiftInHours);
And Joda-Time interoperates well with java.util.Date too. I love it!
If the first argument is a value that will not change often, perhaps use a cache :
static private Map<String,Calendar> dateCache = new HashMap<String,Calendar>();
Then, in your method, check of the first argument (ex: String dateStr) is a key in the cache
Calendar cal;
if (dateCache.containsKey(dateStr)) {
cal = (Calendar)(dateCache.get(dateStr)).clone();
} else {
// parse date
cal = new GregorianCalendar(...);
dateCache.put(dateStr, (Calendar)cal.clone());
}
And add your timeshift value.
How about this,
Parse and hold on to your fixed date, call it fixedDate
Let timeShift be a time shift in hours, then Date shiftedDate = new Date(fixedDate.getTime() + (timeShift * 3600000)) would be your calculated shifted date (see this and this for understanding)
Apply SimpleDateFormat to convert shiftedDate to string.
Repeat steps 2 and 3 indefinitely, fixedDate is not modified and can be reused.
I'd try simple memoisation:
// This is not thread safe. Either give each thread has its own
// (thread confined) converter object, or make the class threadsafe.
public class MyDateConverter {
private String lastDate;
private int lastShift;
private String lastResult;
public String shiftDate(String date, int shift) {
if (shift == lastShift && date.equals(lastDate)) {
return lastResult;
}
// Your existing code here
lastDate = date;
lastShift = shift
lastResult = result;
return result;
}
}
Note this simple approach is most effective if the shift and date values rarely change. If either changes frequently, you'd need a more complicated cache, the code will be more complicated and the overheads (for a cache miss) will be higher.
If you simply want to avoid repeating step 1 (and maybe 2) again and again, parse the date once, then save the Date you get. You can then apply this date to your Calendar (with setDate()) before each add step again (or create a new GregorianCalendar, measure if it matters).

Check a Date is between two dates in Java [duplicate]

This question already has answers here:
How do I check if a date is within a certain range?
(17 answers)
Closed 7 years ago.
One thing I want to know is how to calculate what date will it be 10 days from today.
Second thing is to check if one Date is between two other Dates.
For example, let's say I have an app that shows what events I need to do in the next 10 days (planner). Now how can I see if the date I assigned to an event is between today and the date that is 10 days from today?
Manipulating and comparing dates using java.util.Date and java.util.Calendar is pretty a pain, that's why JodaTime exist. None of the answers as far have covered the time in question. The comparisons may fail when the dates have a non-zero time. It's also unclear whether you want an inclusive or exclusive comparison. Most of the answers posted so far suggest exclusive comparision (i.e. May 24 is not between May 20 and May 24) while in real it would make more sense to make it inclusive (i.e. May 24 is between May 20 and May 24).
One thing I want to know is how to calculate what date will it be 10 days from today.
With the standard Java SE 6 API, you need java.util.Calendar for this.
Calendar plus10days = Calendar.getInstance();
plus10days.add(Calendar.DAY_OF_YEAR, 10);
With JodaTime you would do like this:
DateTime plus10days = new DateTime().plusDays(10);
Second thing is to check if one Date is between two other Dates. For example, let's say I have an app that shows what events I need to do in the next 10 days (planner). Now how can I see if the date I assigned to an event is between today and the date that is 10 days from today?
Now comes the terrible part with Calendar. Let's prepare first:
Calendar now = Calendar.getInstance();
Calendar plus10days = Calendar.getInstance();
plus10days.add(Calendar.DAY_OF_YEAR, 10);
Calendar event = Calendar.getInstance();
event.set(year, month - 1, day); // Or setTime(date);
To compare reliably using Calendar#before() and Calendar#after(), we need to get rid of the time first. Imagine it's currently 24 May 2010 at 9.00 AM and that the event's date is set to 24 May 2010 without time. When you want inclusive comparison, you would like to make it return true at the same day. I.e. both the (event.equals(now) || event.after(now)) or -shorter but equally- (!event.before(now)) should return true. But actually none does that due to the presence of the time in now. You need to clear the time in all calendar instances first like follows:
calendar.clear(Calendar.HOUR);
calendar.clear(Calendar.HOUR_OF_DAY);
calendar.clear(Calendar.MINUTE);
calendar.clear(Calendar.SECOND);
calendar.clear(Calendar.MILLISECOND);
Alternatively you can also compare on day/month/year only.
if (event.get(Calendar.YEAR) >= now.get(Calendar.YEAR)
&& event.get(Calendar.MONTH) >= now.get(Calendar.MONTH)
&& event.get(Calendar.DAY_OF_MONTH) >= now.get(Calendar.DAY_OF_MONTH)
{
// event is equal or after today.
}
Very verbose all.
With JodaTime you can just use DateTime#toLocalDate() to get the date part only:
LocalDate now = new DateTime().toLocalDate();
LocalDate plus10days = now.plusDays(10);
LocalDate event = new DateTime(year, month, day, 0, 0, 0, 0).toLocalDate();
if (!event.isBefore(now) && !event.isAfter(plus10days)) {
// Event is between now and 10 days (inclusive).
}
Yes, the above is really all you need to do.
public static boolean between(Date date, Date dateStart, Date dateEnd) {
if (date != null && dateStart != null && dateEnd != null) {
if (date.after(dateStart) && date.before(dateEnd)) {
return true;
}
else {
return false;
}
}
return false;
}
EDIT: Another suggested variant:
public Boolean checkDate(Date startDate, Date endDate, Date checkDate) {
Interval interval = new Interval(new DateTime(startDate),
new DateTime(endDate));
return interval.contains(new DateTime(checkDate));
}
Use JodaTime calendar replacement classes: http://joda-time.sourceforge.net/
You can use before, after and compareTo methods of Date class.
Here're some examples
http://www.roseindia.net/java/example/java/util/CompareDate.shtml
http://www.javafaq.nu/java-example-code-287.html
http://www.esus.com/javaindex/j2se/jdk1.2/javautil/dates/comparingdates.html
And here's API on Date class
http://java.sun.com/j2se/1.4.2/docs/api/java/util/Date.html
Good Luck!
To add ten days:
Date today = new Date();
Calendar cal = new GregorianCalendar();
cal.setTime(today);
cal.add(Calendar.DAY_OF_YEAR, 10);
To check if between two dates:
myDate.after(firstDate) && myDate.before(lastDate);
To check if date is between two dates, here is simple program:
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
String oeStartDateStr = "04/01/";
String oeEndDateStr = "11/14/";
Calendar cal = Calendar.getInstance();
Integer year = cal.get(Calendar.YEAR);
oeStartDateStr = oeStartDateStr.concat(year.toString());
oeEndDateStr = oeEndDateStr.concat(year.toString());
Date startDate = sdf.parse(oeStartDateStr);
Date endDate = sdf.parse(oeEndDateStr);
Date d = new Date();
String currDt = sdf.format(d);
if((d.after(startDate) && (d.before(endDate))) || (currDt.equals(sdf.format(startDate)) ||currDt.equals(sdf.format(endDate)))){
System.out.println("Date is between 1st april to 14th nov...");
}
else{
System.out.println("Date is not between 1st april to 14th nov...");
}
}
I took the initial answer and modified it a bit. I consider if the dates are equal to be "inside"..
private static boolean between(Date date, Date dateStart, Date dateEnd) {
if (date != null && dateStart != null && dateEnd != null) {
return (dateEqualOrAfter(date, dateStart) && dateEqualOrBefore(date, dateEnd));
}
return false;
}
private static boolean dateEqualOrAfter(Date dateInQuestion, Date date2)
{
if (dateInQuestion.equals(date2))
return true;
return (dateInQuestion.after(date2));
}
private static boolean dateEqualOrBefore(Date dateInQuestion, Date date2)
{
if (dateInQuestion.equals(date2))
return true;
return (dateInQuestion.before(date2));
}

Categories

Resources