Does anybody know how to set date range limit to a datePicker JavaFX 8?
For example I would like to limit this datePicker only for the actual month (september)
Thanks a lot in advance.
Best regards.
Below code is to restrict DatePicker for Date Rage from Jan2000 to tillDate.
restrictDatePicker(datePicker, LocalDate.of(2000, Month.JANUARY, 1), LocalDate.now());
We can change the min and max Date value as per requirement.
public void restrictDatePicker(DatePicker datePicker, LocalDate minDate, LocalDate maxDate) {
final Callback<DatePicker, DateCell> dayCellFactory = new Callback<DatePicker, DateCell>() {
#Override
public DateCell call(final DatePicker datePicker) {
return new DateCell() {
#Override
public void updateItem(LocalDate item, boolean empty) {
super.updateItem(item, empty);
if (item.isBefore(minDate)) {
setDisable(true);
setStyle("-fx-background-color: #ffc0cb;");
}else if (item.isAfter(maxDate)) {
setDisable(true);
setStyle("-fx-background-color: #ffc0cb;");
}
}
};
}
};
datePicker.setDayCellFactory(dayCellFactory);
}
Refer link : https://docs.oracle.com/javase/8/javafx/user-interface-tutorial/date-picker.htm#CCHEBIFF
Related
I am using the following codes for getting the next and previous day details with a selected day. I have 2 buttons named next and previous for getting the next previous dates.
//Saving the current date
string selectedDate = DateTime.Now.ToString("dd-MM-yyyy");
//Previous day
public void PrevButtonClicked(object sender, EventArgs args)
{
DateTimeOffset dtOffset;
if (DateTimeOffset.TryParse(selectedDate, null, DateTimeStyles.None, out dtOffset))
{
DateTime myDate = dtOffset.DateTime;
selectedDate = myDate.AddDays(-1).ToString("dd-MM-yyyy");
}
}
//Next day
public void NextButtonClicked(object sender, EventArgs args)
{
DateTimeOffset dtOffset;
if (DateTimeOffset.TryParse(selectedDate, null, DateTimeStyles.None, out dtOffset))
{
DateTime myDate = dtOffset.DateTime;
selectedDate = myDate.AddDays(+1).ToString("dd-MM-yyyy");
}
}
If I click the previous button I get 03-04-2019 as the result. If again pressed the previous button I get 02-10-2019. Same for the next buttons. Based on the selected date, it will return the next or previous date.
This feature working perfectly in android and windows. But in ios getting the wrong result with this code. Is this the correct way of achieving this feature?
You can improve your code . I create a sample with a Label to display the current date.
in xaml
<StackLayout VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand" Orientation="Horizontal">
<Button Text="Preview" Clicked="PrevButtonClicked"/>
<Label x:Name="dateLabel" TextColor="Red" WidthRequest="100"/>
<Button Text="Next" Clicked="NextButtonClicked"/>
</StackLayout>
in code Behind
public partial class MainPage : ContentPage
{
int year, month, day;
public MainPage()
{
InitializeComponent();
dateLabel.Text = DateTime.Now.ToString("dd-MM-yyyy");
year = DateTime.Now.Year;
month = DateTime.Now.Month;
day= DateTime.Now.Day;
}
private void Button_Clicked(object sender, EventArgs e)
{
DateTime nowDate = new DateTime(year, month, day);
var previewDate = nowDate.AddDays(-1);
dateLabel.Text = previewDate.ToString("dd-MM-yyyy");
year = previewDate.Year;
month = previewDate.Month;
day = previewDate.Day;
}
private void Button_Clicked_1(object sender, EventArgs e)
{
DateTime nowDate = new DateTime(year, month, day);
var nextDate = nowDate.AddDays(+1);
dateLabel.Text = nextDate.ToString("dd-MM-yyyy");
year = nextDate.Year;
month = nextDate.Month;
day = nextDate.Day;
}
}
we tried to validate a javafx datepicker. So we use:
if (fromDatePicker.getValue() == null) {
sb.append("No valid from date!\n");
} else {
System.out.println(fromDatePicker.getValue().toString());
if (!DateUtil
.validEnglishDate(fromDatePicker.getValue().toString())) {
sb.append("No valid from date. Use the format yyyy-MM-dd.\n");
}
}
But at the moment it's impossible to get an invalid Date with the datepicker, because all invalid date's are changed to the start value.
So we asked us is it possible to get an invalid Date with the javafx datepicker?
***** EDIT *****
Example: we have the following datepicker:
DatePicker[2015-05-12]
now we entered "fjdfk" in the DatePicker so we have:
DatePicker[fjdfk]
on save the data's the datepicker changes automatical to DatePicker[2015-05-12]
You could use the DatePicker#setConverter(StringConverter<LocalDate>) to catch any parse exception and warn the user in consequence. Here is a sample :
public class SecureLocalDateStringConverter extends StringConverter<LocalDate> {
/**
* The date pattern that is used for conversion. Change as you wish.
*/
private static final String DATE_PATTERN = "dd/MM/yyyy";
/**
* The date formatter.
*/
public static final DateTimeFormatter DATE_FORMATTER =
DateTimeFormatter.ofPattern(DATE_PATTERN);
private boolean hasParseError = false;
public boolean hasParseError(){
return hasParseError;
}
#Override
public String toString(LocalDate localDate) {
return DATE_FORMATTER.format(localDate);
}
#Override
public LocalDate fromString(String formattedString) {
try {
LocalDate date=LocalDate.from(DATE_FORMATTER.parse(formattedString));
hasParseError=false;
return date;
} catch (DateTimeParseException parseExc){
hasParseError=true;
return null;
}
}
}
From your control, you'll just have to call converter#hasParseError(), converter being the one you set with DatePicker#setConverter(StringConverter<LocalDate>)
Has anyone created a CustomConvertor class for Jersey2 to convert
ISO 8601 dates to Date /Epoch time?
I pass date as query param in ISO_8601_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; I need to convert to epoch seconds. I have all that is necessary, I am lost in gluing it up.
I want the custom convertor to kick in once we see the DateEpochMarker interface. I use jersey 2
what is step which I am missing?
Could some one please help me out?
I have a customer Convertor, a marker Interface and resource method.
public class DateToEpochConvertor implements ParamConverter<Long> {
private static final String ISO_8601_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
#Override
public Long fromString(String value) {
DateFormat df1 = new SimpleDateFormat(ISO_8601_FORMAT);
Date date = new Date();
try {
date = df1.parse(value);
} catch (ParseException e) {
throw new WebApplicationException("The Date "+value+" is not in the ISO 8601 Format ");
}
return date.getTime();
}
#Override
public String toString(Long value) {
DateFormat df1 = new SimpleDateFormat(ISO_8601_FORMAT);
Date dt = new Date();
dt.setTime(value);
return df1.format(dt);
}
}
Marker Interface
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.PARAMETER)
public #interface DateEpochMarker {}
Resource Method
#GET
#Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
#Path("/epochtime")
public Long getEpochTime(#DateEpochMarker #QueryParam("startTime") Long startEpochTime){
return startEpochTime;
}
I feel foolish to answer my own Question.
Somehow I was not been able to make the above working, what I ended up was using custom Jodatime Convertor.
Pasting the code so that anyone stumbling upon the same query might have a answer
#Provider
public class DateTimeParamConverterProvider implements ParamConverterProvider {
private static final Logger LOGGER = org.slf4j.LoggerFactory.getLogger(DateTimeParamConverterProvider.class);
#Override
public <T> ParamConverter<T> getConverter(Class<T> type, Type genericType, Annotation[] annotations) {
if (type.equals(DateTime.class)) {
return (ParamConverter<T>) new DateTimeParamConverter();
} else {
return null;
}
}
private static class DateTimeParamConverter implements ParamConverter<DateTime> {
#Override
public DateTime fromString(String value) {
LOGGER.debug("The ISO Date that is provided is {}", value);
try {
return ISODateTimeFormat.dateTimeNoMillis().parseDateTime(value);
} catch (IllegalArgumentException e) {
return ISODateTimeFormat.dateTime().parseDateTime(value);
}
}
#Override
public String toString(DateTime value) {
return value.toString();
}
}
}
I currently use smartGwt (version 2.5) inside an other framework (Broadleaf).
When i set the locale to french :
Date fields are well formated (DD/MM/YYYY) and the calendar is translated in french but when i change the date and save the form a popup appear with the error message :"Doit ĂȘtre une date" (Must be a date in english). The validator expect a date with MM/DD/YYYY format.
Link to the class used by the framework to create the date field : https://github.com/BroadleafCommerce/BroadleafCommerce/blob/BroadleafCommerce-2.2.x/admin/broadleaf-open-admin-platform/src/main/java/org/broadleafcommerce/openadmin/client/datasource/dynamic/module/BasicClientEntityModule.java
I found a post with same problem (forums.smartclient.com/showthread.php?t=19847) but there is no answer.
Please, let me know how to solve this problem
EDIT :
What i have tried :
#Override
public void onModuleLoad() {
DateUtil.setShortDateDisplayFormat(DateDisplayFormat.TOEUROPEANSHORTDATE);
DateUtil.setShortDateDisplayFormatter(new DateDisplayFormatter() {
#Override
public String format(Date date) {
if(date == null)
{
return null;
}
else{
final DateTimeFormat dateFormatter = DateTimeFormat.getFormat("DD/MM/YYYY");
return dateFormatter.format(date);
}
}
});
Because the code below is not allowed :
DateUtil.setShortDateDisplayFormatter(DateUtil.TOEUROPEANSHORTDATE);
I put my code during the application initialization but the problem still present :-(
Screenshot : http://www.hostingpics.net/viewer.php?id=989088date.png
Do you have an other idea?
Set date formatter of the field to DateDisplayFormat.TOEUROPEANSHORTDATE.
dateItem.setDateFormatter(DateDisplayFormat.TOEUROPEANSHORTDATE);
Also check display seconds in DateTimeItem (SmartGWT) to find another way to set a custom formatted date string when dateItem.useTextField is true.
As the forum thread indicates, its also possible to set default date/datetime format for the application using methods of com.smartgwt.client.util.DateUtil, which should be used only once, during application initialization (e.g.- EntryPoint).
DateUtil.setShortDateDisplayFormatter(DateUtil.TOEUROPEANSHORTDATE);
Problem solved !
You have to use the code below during application initialization :
private static final String DATE_FORMAT = "dd/MM/yyyy HH:mm";
public void onModuleLoad() {
DateUtil.setShortDateDisplayFormatter(new DateDisplayFormatter() {
#Override
public String format(Date date) {
if(date != null)
{
final DateTimeFormat dateFormatter = DateTimeFormat.getFormat(DATE_FORMAT);
return dateFormatter.format(date);
}
return null;
}
});
DateUtil.setDateParser(new DateParser()
{
public Date parse(String dateString)
{
try{
if(dateString != null){
final DateTimeFormat format = DateTimeFormat.getFormat(DATE_FORMAT);
return format.parse(dateString);
}
}catch(Exception e){
e.printStackTrace();
}
return null;
}
});
}
I am using following code.
But addvaluechangedHandler fires twice in gwt.
what other method should i use so that it will occur only once?
calendar.addValueChangeHandler(new ValueChangeHandler<Date>() {
#Override
public void onValueChange(ValueChangeEvent<Date> event) {
Date newDate = calendar.getValue();
newDate.setDate(newDate.getDate()+1);
if ((newDate.before(todaysDate))) {
Window.alert("You can not choose past dates before " +todaysDate);
calendar.setValue(null);
}
}
});
See http://code.google.com/p/google-web-toolkit/issues/detail?id=4785
The workaround seems to be:
public class DateBoxOneEvent extends DateBox {
#Override
public void setValue(Date date, boolean fireEvents) {
if (date != null) {
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
}
super.setValue(date, fireEvents);
}
}