I have to display a page only if the following condition is satisfied i.e
if(system_date >=start_date){
if(system_date<=End_date){
//Do some thing
}
}
Say for example start_date = 08-03-2011 and end_date = 10-03-2011.
I am not able to figure this out. kindly help.
Date now = new Date();
if ((now.after(startDate) || now.equals(startDate)) && ((now.before.endDate) || now.equals(endDate))
{
// do something
}
I agree that Joda Time is very good, but you'll have to weigh whether this simple requirement is worth another JAR dependency. Sometimes you just need something simple.
As OrangeDog suggests, I'd use Joda Time.
You can create a DateTime or an Instant for the start dates and end dates, then use something like:
if (startDate.isBeforeNow() && endDate.isAfterNow())
or perhaps
DateTime now = new DateTime(); // Possibly provide time zone etc if you want
if (startDate.compareTo(now) <= 0 && now.compareTo(endDate) <= 0)
Or even:
Interval valid = new Interval(startDate, endDate);
if (valid.containsNow())
Basically you've got lots of options depending on your exact requirements :)
If you don't want to use an external lib, you can use Calendar's setTime() to create a Calendar out of a given date and then use compareTo to compare two calendar instances.
Calendar start = Calendar.getInstance();
start.setTime(startDate);
Calendar current = Calendar.getInstance();
current.setTime(systemDate);
Calendar end = Calendar.getInstance();
end.setTime(endDate);
if (current.compareTo(start) > 0 && current.compareTo(end) < 0) {
//Do some thing
}
Of course, you have to take care of Timezones and Locales when creating the Calendar instances.
Related
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.
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.
I'm trying to do a simple date comparison between yesterday and today
if (yesterday.before(today)) {
...
}
The issue is that with the before method I will eval to true even if it's just a few seconds difference. How might I compare just the day (because I only want to eval this to true if it was the previous day (minutes/seconds should be ignored)
Thank you in advance
using DateUtils -
if (!DateUtils.isSameDay(yesterday, today) && (yesterday.before(today)) {
//...
}
EDIT: it can be done without DateUtils as well. See this thread.
If you don't want to use a 3rd party library implement a method like this:
public boolean before(Calendar yesterday, Calendar today) {
if(yesterday == today) return false;
if(yesterday == null || today == null) return false;
return yesterday.get(Calendar.YEAR) < today.get(Calendar.YEAR) ? true :
yesterday.get(Calendar.YEAR) == today.get(Calendar.YEAR) && yesterday.get(Calendar.DAY_OF_YEAR) < today.get(Calendar.DAY_OF_YEAR);
}
If you're up to adding a library that handles dates better than the standard Java libraries, you might want to look at Joda.
Using Joda, you can compute difference between days by:
Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();
where startDate and endDate are the Joda version of dates, DateTime (actually a superclass of that).
Converting Java Date objects to Joda DateTime objects can be done by a constructor call:
DateTime dateTime = new DateTime(javaDate);
Adding this library may be overkill for this specific problem, but if you deal with date and time manipulation a lot, the library is definitely worth it.
If you want to stick to Date you could temporarily lower your current date by one day. If before() still leads to the same result you have a timespan of at least one day.
final static long DAY_MILLIS = 86400000;
Date d1 = new Date(2011, 06, 18);
Date d2 = new Date(2011, 06, 16);
Date temp = new Date(d1.getTime() - DAY_MILLIS);
if (temp.before(d2))
// Do stuff
}
Please note I used a deprecated constructor but it should do the job.
I am working with the Java Calendar class to do the following:
Set a start date
Set an end date
Any date within that range is a "valid" date
I have this somewhat working, and somewhat not. Please see the code below:
nowCalendar.set(Calendar.DATE, nowCalendar.get(Calendar.DATE) + offset);
int nowDay = nowCalendar.get(Calendar.DATE);
Calendar futureCalendar = Calendar.getInstance();
futureCalendar.set(Calendar.DATE, nowDay + days);
Date now = nowCalendar.getTime();
Date endTime = futureCalendar.getTime();
long now_ms = now.getTime();
long endTime_ms = endTime.getTime();
for (; now_ms < endTime_ms; now_ms += MILLIS_IN_DAY) {
valid_days.addElement(new Date(now_ms));
System.out.println("VALID DAY: " + new Date(now_ms));
}
Basically, I set a "NOW" calendar and a "FUTURE" calendar, and then I compare the two calendars to find the valid days. On my calendar, valid days will be shaded white and invalid days will be shaded gray. You will notice two variables:
offset = three days after the current selected date
days = the number of valid days from the current selected date
This works...EXCEPT when the current selected date is the last day of the month, or two days prior (three all together). I think that its the offset that is definitely screwing it up, but the logic works everywhere else. Any ideas?
Don't fiddle with milliseconds. Clone the nowCalendar, add 1 day to it using Calendar#add() in a loop as long as it does not exceed futureCalendar and get the Date out of it using Calendar#getTime().
Calendar clone = nowCalendar.clone();
while (!clone.after(futureCalendar)) {
validDays.add(clone.getTime());
clone.add(Calendar.DATE, 1);
}
(note that I improved validDays to be a List instead of the legacy Vector)
Use add instead of set in the first line, otherwise the month is not adjusted if you are at the month boundary:
nowCalendar.add(Calendar.DATE, offset);
public boolean isInRange(Date d)
{
Calendar cal = Calendar.getInstance();
cal.setTime(d);
return cal.after(startCal) && cal.before(endCal);
}
Here the startCal is the calendar instance of start time and endCal is end time.
I found the problem:
As soon as I set futureCalendar to be a clone of nowCalendar (plus the additional days), then it started working. Thanks for everyone's suggestions!
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));
}