Reputation: 1323
If I have:
DatePicker dp = new DataPicker();
and at some point I want to know if the data is greater than today, how can I do it?
Example: if I want to book a room in a hotel from 21/04/2014 well, it should be impossible because today is 28/07/2014.
How can I do it in JavaFX ?
Upvotes: 1
Views: 11816
Reputation: 2408
To ensure that a given Date chosenDate
is after today, you can check
if (chosenDate.after(new Date())) {
// valid (Date > today)
} else {
// invalid (Date <= today)
}
Note that chosenDate
should be a Date
with hour, minute and second set to 0
since else it could accept a Date
with the same day as today but a later hour than now.
Upvotes: 2
Reputation: 5358
You can write a custom method, which will compare given dates of given date format, and return true
, when current date is "older" than your date of interest, eg:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Demo {
public static void main(String args[]) {
System.out.println(isDateOfInterestValid("yyyy-mm-dd",
"2014-08-25", "2014-08-28"));
}
public static boolean isDateOfInterestValid(String dateformat,
String currentDate, String dateOfInterest) {
String format = dateformat;
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date cd = null; // current date
Date doi = null; // date of interest
try {
cd = sdf.parse(currentDate);
doi = sdf.parse(dateOfInterest);
} catch (ParseException e) {
e.printStackTrace();
}
long diff = cd.getTime() - doi.getTime();
int diffDays = (int) (diff / (24 * 1000 * 60 * 60));
if (diffDays > 0) {
return false;
} else {
return true;
}
}
}
And in context of pure JavaFX you can get the String
value of DatePicker
chosen date by calling DatePicker.getValue().toString()
.
PS In case You have only one DatePicker
object, You can use "hidden" method, which will check the current date. It can look like this:
public static String currentDate(String separator) {
Calendar date = new GregorianCalendar();
String day = Integer.toString(date.get(Calendar.DAY_OF_MONTH));
String month = Integer.toString(date.get(Calendar.MONTH) + 1);
String year = Integer.toString(date.get(Calendar.YEAR));
if (month.length() < 2) {
month = "0" + month;
}
if (day.length() < 2) {
day = "0" + day;
}
String regDate = year + separator + month + separator + day;
return regDate;
}
Upvotes: 0