Disable past dates and 2 weeks from now in JCalendar - java

I want to disable past dates and 2 weeks from now from a JCalendar.
I already have this code:
jDateChooser1.getJCalendar().setMinSelectableDate(new Date());
((JTextFieldDateEditor)jDateChooser1.getDateEditor()).setEditable(false);
I already can disable past dates but how about disabling future dates like 2 weeks from now?

As shown here, you can use an IDateEvaluator like MinMaxDateEvaluator to invalidate a range of dates:
private static class RangeEvaluator extends MinMaxDateEvaluator {
#Override
public boolean isInvalid(Date date) {
return !super.isInvalid(date);
}
}
Then you can specify a range of invalid dates, e.g. a day before and two weeks after:
Calendar min = Calendar.getInstance();
min.add(Calendar.DAY_OF_MONTH, -1);
Calendar max = Calendar.getInstance();
max.add(Calendar.DAY_OF_MONTH, 13);
RangeEvaluator re = new RangeEvaluator();
re.setMinSelectableDate(min.getTime());
re.setMaxSelectableDate(max.getTime());
JCalendar jc = new JCalendar();
jc.getDayChooser().addDateEvaluator(re);
jc.setCalendar(jc.getCalendar());
Note that you can add multiple instances of RangeEvaluator to handle different ranges.

I haven't tried this but I imagine using a date in the future would do this:
Date d = new Date();
d.setTime(d.getTime() + 14 * 86400 * 1000); -- set the date 14 days forward
jDateChooser1.getJCalendar().setMinSelectableDate(d);
((JTextFieldDateEditor)jDateChooser1.getDateEditor()).setEditable(false);
Instead of working with a Date object and having to use setTime(milliseconds) you might want to use a proper Calendar object which has better methods for altering the date and so on.
Calendar cal = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, 14);
Date twoweeks = calendar.getTime();

I already have answered my own question by the help of trashgod's code.
Here:
Calendar min = Calendar.getInstance();
min.add(Calendar.DAY_OF_MONTH, 15);
Calendar max = Calendar.getInstance();
max.add(Calendar.DAY_OF_MONTH, 2000000);
RangeEvaluator re = new RangeEvaluator();
re.setMinSelectableDate(min.getTime());
re.setMaxSelectableDate(max.getTime());
// JCalendar jc = new JCalendar();
jDateChooser1.getJCalendar().setMinSelectableDate(min.getTime());
jDateChooser1.getJCalendar().setMaxSelectableDate(max.getTime());
((JTextFieldDateEditor)jDateChooser1.getDateEditor()).setEditable(false);
Thanks! :D

Related

How can I check if date is before a specific time?

I have to check, if a date variable is before a specific time. The variable has the format dd.MM.yyyy HH:mm:ss.
Let's take todays date 31.10.2016 15:20:45. The value of the variable is 30.10.2016 14:00:21. How can I check now if the variable is one day older than today and if the time is before or equals 23:00?
I tried following code.
Date today = new Date();
Calendar c = Calendar.getInstance();
c.setTime(causedAt);
c.add(Calendar.DATE, 1);
if (c.getTime().compareTo(today) < 0) { // It's more than 1 day.
setOneDayOverdue(true);
setFiveDaysOverdue(false);
}
But with this code the part with the time is missing.
The solution should work with Java 7 and without any external libraries like Joda-Time.
You should use the new Java 8 Date / Time API:
LocalDateTime NOW = LocalDateTime.now(); // e.g. 31.10.2016 15:20:45
// parse given Date/Time
LocalDateTime input = LocalDateTime.parse(strInput, DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss"));
// Check if input is before "now"
boolean isBefore = input.isBefore(NOW);
See https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html to get all the methods you need to meet your requirements. For example:
LocalDateTime yesterday = NOW.minusDays(1);
boolean isBeforeYesterday = input.isBefore(yesterday);
With getHour() and getMinute() you can check for <= 23:00. Or you can use LocalTime but it seems getting those two fields should be enough for you.
So I got following code that works for me:
public void setOverdueFlagIfRequired(Date today, Date causedAtDate) {
Calendar now = Calendar.getInstance();
now.setTime(today);
Calendar causedAt = Calendar.getInstance();
causedAt.setTime(causedAtDate);
Calendar yesterday2300 = Calendar.getInstance();
yesterday2300.setTime(today);
yesterday2300.add(Calendar.DATE, -1);
yesterday2300.set(Calendar.HOUR_OF_DAY, 23);
yesterday2300.set(Calendar.MINUTE, 0);
yesterday2300.set(Calendar.SECOND, 0);
yesterday2300.set(Calendar.MILLISECOND, 0);
Calendar fiveDaysBack2300 = Calendar.getInstance();
fiveDaysBack2300.setTime(yesterday2300.getTime());
fiveDaysBack2300.add(Calendar.DATE, -4);
if (causedAt.compareTo(fiveDaysBack2300)<=0) {
setFiveDaysOverdue(true);
}
else if (causedAt.compareTo(yesterday2300)<=0 && causedAt.compareTo(fiveDaysBack2300)>0) {
setOneDayOverdue(true);
}
}

How do I add 2 weeks to a Date in java? [duplicate]

This question already has answers here:
Modify the week in a Calendar
(4 answers)
Closed 5 years ago.
I am getting a Date from the object at the point of instantiation, and for the sake of outputting I need to add 2 weeks to that date. I am wondering how I would go about adding to it and also whether or not my syntax is correct currently.
Current Java:
private final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
private Date dateOfOrder;
private void setDateOfOrder()
{
//Get current date time with Date()
dateOfOrder = new Date();
}
public Date getDateOfOrder()
{
return dateOfOrder;
}
Is this syntax correct? Also, I want to make a getter that returns an estimated shipping date, which is 14 days after the date of order, I'm not sure how to add and subtract from the current date.
Use Calendar and set the current time then user the add method of the calendar
try this:
int noOfDays = 14; //i.e two weeks
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateOfOrder);
calendar.add(Calendar.DAY_OF_YEAR, noOfDays);
Date date = calendar.getTime();
I will show you how we can do it in Java 8. Here you go:
public class DemoDate {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println("Current date: " + today);
//add 2 week to the current date
LocalDate next2Week = today.plus(2, ChronoUnit.WEEKS);
System.out.println("Next week: " + next2Week);
}
}
The output:
Current date: 2016-08-15
Next week: 2016-08-29
Java 8 rocks !!
Use Calendar
Date date = ...
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.WEEK_OF_MONTH, 2);
date = c.getTime();
Try this to add two weeks.
long date = System.currentTimeMillis() + 14 * 24 * 3600 * 1000;
Date newDate = new Date(date);
if pass 14 to this addDate method it will add 14 to the current date and return
public String addDate(int days) throws Exception {
final DateFormat dateFormat1 = new SimpleDateFormat(
"yyyy/MM/dd HH:mm:ss");
Calendar c = Calendar.getInstance();
c.setTime(new Date()); // Now use today date.
c.add(Calendar.DATE, addDays); // Adding 5 days
return dateFormat1.format(c.getTime());
}
Using the Joda-Time library will be easier and will handle Daylight Saving Time, other anomalies, and time zones.
java.util.Date date = new DateTime( DateTimeZone.forID( "America/Denver" ) ).plusWeeks( 2 ).withTimeAtStartOfDay().toDate();
If you are on java 8 you can use new date time api http://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html#plusWeeks-long-
if you are on java 7 or more old version of java you should use old api http://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#add-int-int-

How to set a Java Date object's value to yesterday? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Get yesterday's date using Date
What is an elegant way set to a Java Date object's value to yesterday?
With JodaTime
LocalDate today = LocalDate.now();
LocalDate yesterday = today.minus(Period.days(1));
System.out.printf("Today is : %s, Yesterday : %s", today.toString("yyyy-MM-dd"), yesterday.toString("yyyy-MM-dd"));
Do you mean to go back 24 hours in time.
Date date = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000L);
or to go back one day at the time same time (this can be 23 or 25 hours depending on daylight savings)
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
These are not exactly the same due to daylight saving.
Convert the Date to a Calendar object and "roll" it back a single day. Something like this helper method take from here:
public static void addDays(Date d, int days)
{
Calendar c = Calendar.getInstance();
c.setTime(d);
c.add(Calendar.DATE, days);
d.setTime(c.getTime().getTime());
}
For your specific case, just pass in days as -1 and you should be done. Just make sure you take into consideration the timezone/locale if doing extensive date specific manipulations.
you can try the follwing code:
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Today's date is "+dateFormat.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime()));
As many people have already said use Calendar rather than date.
If you find you really want to use dates:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR, -24);
cal.getTime();//returns a Date object
Calendar cal1 = Calendar.getInstance();
cal1.add(Calendar.DAY_OF_MONTH, -1);
cal1.getTime();//returns a Date object
I hope this helps.
tomred
You can try the following example to set it to previous date.
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
System.out.println("Today's date is " +dateFormat.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime()));

Compare dates using Calendar class using java

The user entered date is using a drop down separately for day, month and year. I have to compare the user entered date with today's date and check if it is same day or future day. I am a bit confused about the time portion because I am not interested in time, just the date. How to solve this without using the Date class (I read it is not recommended to use Date class).
Thanks.
You first need to create GregorianCalendar instance representing entered date:
Calendar user = new GregorianCalendar(2012, Calendar.MAY, 17);
And one for "now":
Calendar now = new GregorianCalendar();
This will yield positive value if date is in the future and negative - if in the past:
user.compareTo(now);
Few notes about constructing user object:
it uses current JVM time zone, so in my case it is midnight, 17th of May in CEST time zone
be careful with months, they are 0-based
Try class DateUtils of library Apache Commons Lang.
This class provides the method truncatedEquals(cal1, cal2, field).
So you can check for equality with a single line of code:
Calendar user = new GregorianCalendar(2012, Calendar.MAY, 17);
Calendar now = Calendar.getInstance();
if(DateUtils.truncatedEquals(user, now, Calendar.DATE)){
// your code goes here
}
Simple calculation :
GregorianCalendar gc1 = new GregorianCalendar();
GregorianCalendar gc2 = new GregorianCalendar();
gc2.add(GregorianCalendar.DAY_OF_MONTH, 2); // gc2 is 2 days after gc1
long duration = (gc2.getTimeInMillis() - gc1.getTimeInMillis() )
/ ( 1000 * 60 * 60 * 24) ;
System.out.println(duration);
-> 2
Use a gregorian calendar.
If you wanted to know the number of days difference between two dates then you could make a method similar to the following.
public int getDays(GregorianCalendar g1, GregorianCalendar g2) {
int elapsed = 0;
GregorianCalendar gc1, gc2;
if (g2.after(g1)) {
gc2 = (GregorianCalendar) g2.clone();
gc1 = (GregorianCalendar) g1.clone();
}
else {
gc2 = (GregorianCalendar) g1.clone();
gc1 = (GregorianCalendar) g2.clone();
}
gc1.clear(Calendar.MILLISECOND);
gc1.clear(Calendar.SECOND);
gc1.clear(Calendar.MINUTE);
gc1.clear(Calendar.HOUR_OF_DAY);
gc2.clear(Calendar.MILLISECOND);
gc2.clear(Calendar.SECOND);
gc2.clear(Calendar.MINUTE);
gc2.clear(Calendar.HOUR_OF_DAY);
while ( gc1.before(gc2) ) {
gc1.add(Calendar.DATE, 1);
elapsed++;
}
return elapsed;
}
That would return you the difference in the number of days.
Try this solution:
int day = 0; //user provided
int month = 0; //user provided
int year = 0; //user provided
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONDAY, month);
calendar.set(Calendar.DAY_OF_MONTH, day);
long millisUser = calendar.getTime().getTime();
long nowMillis = System.currentTimeMillis();
if(nowMillis < millisUser) {
...
}
Above is check if date is in future.
There is nothing wrong in using java.util.Date
You can use:
int day = 0; //user provided
int month = 0; //user provided
int year = 0; //user provided
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONDAY, month);
calendar.set(Calendar.DAY_OF_MONTH, day);
Date userSubmit = calendar.getTime();
Date now = new Date();
if(userSubmit.after(now)) {
...
}
But if you want fluent, easy and intuitive API with dates I recommend using JodaTime

How to determine tomorrow's date in J2ME for use in a DateField?

I basically want to be able to show tomorrows date
I have this which shows today date
private Date date = new Date();
i tried this but this gave me jan 1 1970
private Date date = new Date(+1);
please help
The integer (actually long) parameter for the Date constructor is for specifying the milliseconds of offset from January 1st, 1970, GMT.
You need to use a Calendar instead
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
Date date = cal.getTime();
Note, the Date.setBlah and Date.getBlah methods are deprecated, Calendar should be used instead. (Not sure if that's available in J2ME though.)
private Date date = new Date();
date.setDate(date.getDate() + 1);
As suggested here, use an implementation of class Calendar like thus:
Calendar myCalendar = Calendar.getInstance();
long tomorrow = myCalendar.getTimeInMillis() + 24 * 60 * 60 * 1000;
myCalendar.setTimeInMillis(tomorrow);
And do whatever you want with that...
Hope this helps,
Yuval =8-)

Categories

Resources