adding/removing days from date code fix needed - java

I have this code here:
public static String AddRemoveDays(String date, int days) throws ParseException
{
SimpleDateFormat k = new SimpleDateFormat("yyyyMMdd");
Date d = k.parse(date);
d = new Date(d.getTime() + days*86400000);
String time = k.format(d);
return time;
}
It take String formed "yyyyMMdd", and adds int days to it. It should work then the days is negative - then he would substract the days from the date. When it does it's math, it returns String formated "yyyyMMdd".
At least that is what it should do. It works for small numbers, but if I try to add (or remove), for example, a year (365 or -365), it returns wierd dates.
What's the problem?
Should I do it a completley another way?

d = new Date(d.getTime() + days*86400000);
If you multiply 86400000 by 365 integer cant hold it. Change 86400000 to Long
d = new Date(d.getTime() + days*86400000L);
and it will be fine.

Hard to say what's going on without specific dates.
If you're committed to doing this with the raw Java classes, you might want to look at using Calendar -e.g.
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
calendar.add(Calendar.DATE, days); // this supports negative values for days;
d = calendar.getTime();
That said, I would recommend steering clear of the java Date classes, and look to use jodaTime or jsr310 instead.
e.g. in jsr310, you could use a DateTimeFormatter and LocalDate:
DateTimeFormatter format = DateTimeFormatters.pattern("yyyyMMdd");
LocalDate orig = format.parse(dateString, LocalDate.rule());
LocalDate inc = orig.plusDays(days); // again, days can be negative;
return format.print(inc);

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

Android : Compare two dates with different time zones [duplicate]

I have 2 date object in the database that represent the company's working hours.
I only need the hours but since I have to save date. it appears like this:
Date companyWorkStartHour;
Date companyWorkEndHour;
start hours: 12-12-2001-13:00:00
finish hours: 12-12-2001-18:00:00
I have the timezone of the company and of the user. (my server may be in another timezone).
TimeZone userTimeZone;
TimeZone companyTimeZone;
I need to check if the user's current time (considering his timezone) is within the company working hours (considering the company's time zone).
How can I do it? I am struggling for over a week with Java calendar and with no success!
The java.util.Date class is a container that holds a number of milliseconds since 1 January 1970, 00:00:00 UTC. Note that class Date doesn't know anyting about timezones. Use class Calendar if you need to work with timezones. (edit 19-Jan-2017: if you are using Java 8, use the new date and time API in package java.time).
Class Date is not really suited for holding an hour number (for example 13:00 or 18:00) without a date. It's simply not made for that purpose, so if you try to use it like that, as you seem to be doing, you'll run into a number of problems and your solution won't be elegant.
If you forget about using class Date to store the working hours and just use integers, this will be much simpler:
Date userDate = ...;
TimeZone userTimeZone = ...;
int companyWorkStartHour = 13;
int companyWorkEndHour = 18;
Calendar cal = Calendar.getInstance();
cal.setTime(userDate);
cal.setTimeZone(userTimeZone);
int hour = cal.get(Calendar.HOUR_OF_DAY);
boolean withinCompanyHours = (hour >= companyWorkStartHour && hour < companyWorkEndHour);
If you also want to take minutes (not just hours) into account, you could do something like this:
int companyWorkStart = 1300;
int companyWorkEnd = 1830;
int time = cal.get(Calendar.HOUR_OF_DAY) * 100 + cal.get(Calendar.MINUTE);
boolean withinCompanyHours = (time >= companyWorkStart && time < companyWorkEnd);
Try something like this:
Calendar companyWorkStart = new GregorianCalendar(companyTimeZone);
companyWorkStart.setTime(companyWorkStartHour);
Calendar companyWorkEnd = new GregorianCalendar(companyTimeZone);
companyWorkEnd.setTime(companyWorkEndHour);
Calendar user = new GregorianCalendar(userTimeZone);
user.setTime(userTime);
if(user.compareTo(companyWorkStart)>=0 && user.compareTo(companyWorkEnd)<=0) {
...
}
I haven't tried the Joda library. This code should work.
public boolean checkUserTimeZoneOverLaps(TimeZone companyTimeZone,
TimeZone userTimeZone, Date companyWorkStartHour,
Date companyWorkEndHour, Date userCurrentDate) {
Calendar userCurrentTime = Calendar.getInstance(userTimeZone);
userCurrentTime.setTime(userCurrentDate);
int year = userCurrentTime.get(Calendar.YEAR);
int month = userCurrentTime.get(Calendar.MONTH);
int day = userCurrentTime.get(Calendar.DAY_OF_MONTH);
Calendar startTime = Calendar.getInstance(companyTimeZone);
startTime.setTime(companyWorkStartHour);
startTime.set(Calendar.YEAR, year);
startTime.set(Calendar.MONTH, month);
startTime.set(Calendar.DAY_OF_MONTH, day);
Calendar endTime = Calendar.getInstance(companyTimeZone);
endTime.setTime(companyWorkEndHour);
endTime.set(Calendar.YEAR, year);
endTime.set(Calendar.MONTH, month);
endTime.set(Calendar.DAY_OF_MONTH, day);
if (userCurrentTime.after(startTime) && userCurrentTime.before(endTime)) {
return true;
}
return false;
}
EDIT
Updated the code to reflect Bruno's comments. Shouldn't be taking the dates of the company work timings.
Hey I am not sure how you would do this using the Java calendar but I would highly recommend using the Joda Time package. It's a much simpler system to use and it gives you direct methods to extracts all subcomponents of data and time and even just to create simple time objects without the date involved. Then I imagine it would be a matter of comparing the 2 timezone differences and subtracting the difference from the JodaTime object.

Get days between two dates?

I am trying to get the days between two values. Which is in the format of MMdd.
Ex:
First Date = 0501
Second Date = 0519
Trying to find the value of days between the two dates. In this example would be 18. Please help me with this. I tried searching around and can't find a solution. Thank you!
My Code
This is what I have so far:
Getting an error: Method days in class Project3 cannot be applied to the given type.
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class Project3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String name = input.next() + input.nextLine();
String car = input.next() + input.nextLine();
String key = input.next();
String firstDate = input.next(), lastDate = input.next();
double S = 1.0, C = 1.2, U = 1.4, T = 1.6, B = 2.0;
final double N = 89.22, V = (N - 11.4);
double daily, total;
String daysBetween = Project3.days();
}
public static long days(Date firstDate, Date lastDate) {
Calendar start = Calendar.getInstance();
start.setTime(firstDate);
Calendar end = Calendar.getInstance();
long daysBetween = 0;
while (start.before(end)) {
start.add(Calendar.DAY_OF_MONTH, 1);
daysBetween++;
}
return daysBetween;
}
}
Using Joda Time Days:
DateTimeFormatter dtf = DateTimeFormat.forPattern("MMdd");
LocalDate day1 = dtf.parseLocalDate("0501");
LocalDate day2 = dtf.parseLocalDate("0519");
int daysBetween = Days.daysBetween(day1, day2).getDays();
Joda time is the right way to do this, but if you really have to do it with pure JDK stuff, you can calculate it yourself.
A Calendar instance has a .getTimeInMillis() method that tells you the number of milliseconds since some fixed start point. You can take two dates, put them into Calendar instances, and then calculate the difference between the two getTimeInMillis() values.
Then divide by 1000 to get seconds; by 60 to get minutes; by 60 to get hours; by 24 to get days. And cross your fingers and hope for the best with regard to daylight saving time.
You have one other issue to get round, which is that since you've only got a day and a month, but not a year, there isn't a unique answer. The difference in days between 28 Feb and 1 Mar is one day in most years, but two days in a leap year. If you want to assume Feb has only 28 days, just choose any non-leap year you like (e.g., 2014).
This is a method for calculating the number of days between two dates. It keeps rolling the day forward, while the start date is before the end date. It works regardless of differences in time due to daylight saving time.
public static long days(Date startDate, Date endDate) {
Calendar start = Calendar.getInstance();
start.setTime(startDate);
Calendar end = Calendar.getInstance();
long daysBetween = 0;
while(start.before(end)) {
start.add(Calendar.DAY_OF_MONTH, 1);
daysBetween++;
}
return daysBetween;
}

Java Calendar returns same millisecond value for two different dates

This is my first question, so please be gentle with me! I am having a problem with some pre-existing java code.
It is pretty simple, you pass it two dates in the format "2013-10-31", it then calculates the ms difference between the two values and then does some more calculations after that. The problem is that every now and again, even though two different dates are passed, they both have the same millisecond value. An example of this is if you pass "2013-10-31" and "2013-11-01", it returns the difference as 0. The ms values both being "1385856000000".
Code is:
public int getTotalStartEndTime( java.sql.Date startdate, java.sql.Date enddate, java.sql.Time starttime, java.sql.Time endtime )
{
if(startdate != null & enddate != null && starttime !=null && endtime!= null){
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
int styr = Integer.parseInt(startdate.toString().substring(0,startdate.toString().indexOf("-")),10);
int stmm = Integer.parseInt(startdate.toString().substring(startdate.toString().indexOf("-")+1,startdate.toString().lastIndexOf("-")),10);
int stdd = Integer.parseInt(startdate.toString().substring(startdate.toString().lastIndexOf("-")+1),10);
int enyr = Integer.parseInt(enddate.toString().substring(0,enddate.toString().indexOf("-")),10);
int enmm = Integer.parseInt(enddate.toString().substring(enddate.toString().indexOf("-")+1,enddate.toString().lastIndexOf("-")),10);
int endd = Integer.parseInt(enddate.toString().substring(enddate.toString().lastIndexOf("-")+1),10);
//calendar1.set(styr, stmm, stdd);
calendar1.set(Calendar.YEAR, styr);
calendar1.set(Calendar.MONTH, stmm);
calendar1.set(Calendar.DAY_OF_MONTH, stdd);
calendar1.set(Calendar.HOUR, 0);
calendar1.set(Calendar.MINUTE, 0);
calendar1.set(Calendar.SECOND, 0);
calendar1.set(Calendar.MILLISECOND,0);
//calendar2.set(enyr, enmm, endd);
calendar2.set(Calendar.YEAR, enyr);
calendar2.set(Calendar.MONTH, enmm);
calendar2.set(Calendar.DAY_OF_MONTH, endd);
calendar2.set(Calendar.HOUR, 0);
calendar2.set(Calendar.MINUTE, 0);
calendar2.set(Calendar.SECOND, 0);
calendar2.set(Calendar.MILLISECOND,0);
long milliseconds1 = calendar1.getTimeInMillis();
long milliseconds2 = calendar2.getTimeInMillis();
long diff = milliseconds2 - milliseconds1;
Any help would be greatly appreciated, as I cannot work out what is happening!
calendar month is 0-11, in your code, you parsing date from string and month 10 is converted to november, which has not 31 days and set to first december.
As it has been said, MONTH is 0-11.
Your code didn't throw an exception since the default value of lenient is true.
You should set it to false (unless you explicitly want this behavior) to detect this kind of situation more easily :
calendar1.setLenient(false);
calendar2.setLenient(false);
It's not actually answering your question, but if all you need is the value of diff, there is no need to work with Calendar instances, but you can replace your code entirely with:
long diff = enddate.getTime() - startdate.getTime();
If you actually need the Calendar objects for other operations, there is still no need to parse the string representation of the dates, you can simply set the Calendar to the Date value with one operation:
Calendar calendar1 = Calendar.getInstance();
calendar1.setTimeInMillis(startdate.getTime());

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