Avoiding picking up future dates in Calendar Codename One - codenameone

I have a Calendar, so I can get dates by:
Calendar cld = new Calendar();
cld.getCurrentDate();
also:
cld.getDate();
So I have the current date and the date which I chose in the Calendar. What I'm trying to do is like:
Date currentdate = cld.getCurrentDate();
Date chosendate = cld.getDate();
long math = Math.abs(currentdate.getTime() - chosendate.getTime());
long result = math / (24 * 60 * 60 * 1000);
if(result < 0)Dialog.show("Invalid Date", "Please select a valid date.", "OK", null);
Not sure if my method is correct, actually I wanna a method to avoid picking up future dates from the Calendar, how to do that in Codename One?
EDITED:
Calendar cld = new Calendar() {
protected void updateButtonDayDate(Component dayButton, int year, int currentMonth, int day) {
super.updateButtonDayDate(dayButton, year, currentMonth, currentDay);
dayButton.setEnabled(isDateValid(year, currentMonth, day));
}
};
My isDateValid() method:
import java.util.Calendar;
public class DateValidator {
public boolean isDateValid(int year, int currentMonth, int day) {
if(Calendar.MONTH < currentMonth-1)return false;
else {
return true;
}
}
}
I had to create a new class since I was already using the Calendar from Codename One in my other Class, and it doesn't provide Calendar.MONTH. I can't pick up future months, but it still allow me to pick up future days and future years. I wish I could use the method Date.after() from the original java.util.Date, the Date from Codename One doesn't have the method after() which is making it difficult for me to find out a way. Any help?

You can derive Calendar and provide that logic yourself:
Calendar cld = new Calendar() {
protected void updateButtonDayDate(Component dayButton, int year, int currentMonth, int day) {
super.updateButtonDayDate(dayButton, year, currentMonth, currentDay);
dayButton.setEnabled(isDateValid(year, currentMonth, day));
}
};
The isDateValid() can be anything in this case only past dates:
private boolean isDateValid(int year, int currentMonth, int day) {
java.util.Calendar cld = java.util.Calendar.getInstance();
cld.set(java.util.Calendar.YEAR, year);
cld.set(java.util.Calendar.MONTH, currentMonth);
cld.set(java.util.Calendar.DAY_OF_MONTH, day);
return cld.getTime().getTime() < System.currentTimeMillis();
}

Related

JCalendar sets to March 30 when February is chosen

Code consists of just month and year can be chosen in jcalendar, by default the day is 30 and 28 for February, the issue comes when I choose February, automatically jcalendar sets to March 30; this is the code; it is in PropertyChange event of jcalendar.
Calendar cal = PFI.getCalendar();
int day = cal.get(Calendar.DAY_OF_MONTH);
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);
if(month==1){
cal.set(year, 1 , 28);
PFI.setCalendar(cal);
}
else
{
cal.set(year, month , 30);
PFI.setCalendar(cal);
}
Combining the suggestions of #Ole V.V. and #Catalina Island, the fragment below illustrates JYearChooser and JMonthChooser in a GridLayout. A common listener then uses java.time to display the last day of the selected year and month.
JPanel panel = new JPanel(new GridLayout(1, 0));
JMonthChooser jmc = new JMonthChooser();
JYearChooser jyc = new JYearChooser();
JLabel label = new JLabel("Last day of month:");
label.setHorizontalAlignment(JLabel.RIGHT);
JTextField last = new JTextField(8);
label.setLabelFor(last);
PropertyChangeListener myListener = new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent e) {
LocalDate ld = LocalDate.of(jyc.getYear(), jmc.getMonth() + 1, 1)
.with(TemporalAdjusters.lastDayOfMonth());
last.setText(ld.format(DateTimeFormatter.ISO_DATE));
}
};
myListener.propertyChange(null);
jmc.addPropertyChangeListener("month", myListener);
jyc.addPropertyChangeListener("year", myListener);
panel.add(jyc);
panel.add(jmc);
panel.add(label);
panel.add(last);

Full Calendar 4.x for the Vaadin Framework 14+ not displaying in 24 hours format

enter image description here I have created a FullCalendar, it is displaying the time in AM/PM. When I am adding the enteries to the calendar, I format the LocalDateTime to 24 hours format but the Calendar displays it in AM/PM format.
How I can display the Calendar entries in 24 hours format?
My Formatter is defined as:
public static final DateTimeFormatter TWENTY_FOUR_HOURS_DATE_TIME_FORMATTER =
DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm:ss", AppConstants.APP_LOCALE);
Entry entry = new Entry();
entry.setEditable(false);
entry.setTitle(game.getHomeClub() + " - " +game.getHomeTeam());
Instant now = Instant.now();
String t = LocalDateTime.of(game.getGameTime().toLocalDate(), game.getGameTime().toLocalTime())
.format(FormattingUtils.TWENTY_FOUR_HOURS_DATE_TIME_FORMATTER);
entry.setStart(calendar.getTimezone().convertToUTC(LocalDateTime.parse(t, FormattingUtils.TWENTY_FOUR_HOURS_DATE_TIME_FORMATTER)));
entry.setEnd(game.getGameTime().plus(2, ChronoUnit.HOURS));
calendar = new MyFullCalendar();
calendar.setWeekNumbersVisible(true);
calendar.setNowIndicatorShown(false);
calendar.setNumberClickable(true);
calendar.changeView(CalendarViewImpl.AGENDA_WEEK);
calendar.setLocale(Locale.GERMANY);
private void createTimedEntry(FullCalendar calendar, String title, String start, int minutes, String color) {
Entry entry = new Entry();
setValues(calendar, entry, title, start, minutes, ChronoUnit.MINUTES, color);
calendar.addEntry(entry);
}
You need to set the Locale.
#Route(value = "test")
class TestView extends Composite<Div> {
TestView() {
Locale defaultLocale = Locale.GERMANY
FullCalendar calendar = FullCalendarBuilder.create().build()
calendar.changeView(CalendarViewImpl.TIME_GRID_DAY)
calendar.setSizeFull()
RadioButtonGroup<Locale> localeSwitcher = new RadioButtonGroup()
localeSwitcher.setItems([defaultLocale, Locale.US])
localeSwitcher.addValueChangeListener({ ev ->
calendar.setLocale(localeSwitcher.value)
})
localeSwitcher.setValue(defaultLocale)
VerticalLayout layout = new VerticalLayout(localeSwitcher, calendar)
layout.setSizeFull()
content.add(layout)
}
}
Code (Groovy) above produces following calendar for German Locale:
and this for US Locale:
I know, the question is a bit old, but this answer may help anyone who is still searchting for an answer :)
Regardless of any i18n settings, you may use initial options on the server side to modifiy the event time format.
JsonObject initialOptions = Json.createObject();
JsonObject eventTimeFormat = Json.createObject();
//{ hour: 'numeric', minute: '2-digit', timeZoneName: 'short' }
eventTimeFormat.put("hour", "2-digit");
eventTimeFormat.put("minute", "2-digit");
eventTimeFormat.put("meridiem", false);
eventTimeFormat.put("hour12", false);
initialOptions.put("eventTimeFormat", eventTimeFormat);
FullCalendar calendar = FullCalendarBuilder.create()
.withInitialOptions(defaultInitialOptions)
// ...
.build();
Any initial options you can use you may obtain from the native library docs: https://fullcalendar.io/docs/eventTimeFormat (and other pages)

Richfaces Calendar Today Date

I am trying to change the "today" date in richfaces calendar module. I could not find anything in the CalendarDataModel provided by richfaces thus im trying to find the answer here. I am not talking about the selected date.
Use Case:
I am opening the calendar by clicking on the input and instead of current day and the preselected current month I want to get displayed November the 14th.
Wider explanation:
I have two different inputs which depend on each other. The date selected in the first input should be the "today" date in the second input.
Thank you for any suggestions.
Following code sets date from first calendar to second and rerender second calendar component. Code not sets today date for second calendar. System date is used as today date and it is the same date for first and second calendars. Code:
<h:panelGrid columns="2">
<h:outputLabel for="from" value="From" />
<rich:calendar id="from" value="#{t1Calendar.from}"
datePattern="dd/MM/yyyy" enableManualInput="true">
<a4j:ajax event="change" render="to"/>
</rich:calendar>
<h:outputLabel for="to" value="To" />
<rich:calendar id="to" value="#{t1Calendar.to}"
datePattern="dd/MM/yyyy" enableManualInput="true" popup="true"/>
</h:panelGrid>
and
#ManagedBean
public class T1Calendar {
private Date from = new Date();
private Date to;
public Date getFrom() { return from; }
public void setFrom(Date from) {
this.from = from;
this.to = from;
}
public Date getTo() { return to; }
public void setTo(Date to) { this.to = to; }
}

App-engine query

I am new to app-engine Datastore and to NoSQL world in common. I am developing a simple application where a user can declare his/her expenses everyday. Every user(Account) has its own declared expenses. The dash board contains a simple GWT Cell Tree which contains all the years in which the use declared expenses and when he/she clicks on a years, he gets all the months of the years then he clicks on the month and he gets all the days of the month and finally clicking on a day and he gets all the expenses declared in that day. It is something like
*2010
|_ jan
|_1
|_2
|_Food 12d
|_Dress 200d
|_Fun 150d
|_ ...
|_ feb
|_ ...
*2011
|_ jan
|_ feb
|_...
I save expenses entities in the data store for each user(Account) as the account the parent of all the expenses. my expense is as follow:
public class Expense implements Serializable, Comparable {
private String name;
private double price;
private Date date;
public Expense(String name, double price, Date date) {
this.name = name;
this.price = price;
this.date = date;
}
public Expense() {
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public boolean isPriceValid() {
return price > 0;
}
public void setName(String name) {
this.name = name;
}
public void setPrice(double price) {
this.price = price;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
#Override
public int compareTo(Expense expense) {
if (name.equals(expense.getName())) {
if (date.equals(expense.getDate())) {
return new Double(price).compareTo(expense.getPrice());
}
return date.compareTo(expense.getDate());
}
return name.compareTo(expense.getName());
}
My QUESTION IS: How to query the expenses in the data store and return all different years relater to a specified Account and put them in a list or set or anything else where I can list them ? does I need to fetch all the expenses entities and iterate over them and get all the different years. doesn't sound reasonable. Any advice will be welcome and THANKS IN ADVANCE.
Several comments related to your post :
--> I wouldn't store a financial amount as a Double. Going that route will lead you to big problems with rounding errors. There are a lot of posts on this one. I would suggest you to store it as "DollarCent" and declare it as an integer. You simply multiply the amount by 100 when you store it and when displaying it you divide by 100.
--> Why do you declare your entity in the Datastore as implementing Serializable ? I would store without Serializable.
--> Related to the specific question on displaying the data by year, reading your question I see no other way than fetching the data. What I would do is ask GAE to order the data to avoid having to order it afterwards. Using Objectify, it would simply be q.filter(...).order(-date).order(amount).
Hope this helps !
Hugues

Silverlight Datagrid grouping by year, month, week

I am using Silverlight RIA with EF and I have an entity with e.g. fields Date, Field1, Field2, ...
Binding the data on LoadOperation_Completed works fine. However, I need to group the data by Year, Month, Week. What is the proposed method? I've tried
public void loadOp_Completed(object sender, EventArgs e) {
LoadOperation<MyEntity> loadOp = sender as LoadOperation<MyEntity>;
List<MyEntity> list = ((LoadOperation<MyEntity>)sender).Entities.ToList();
PagedCollectionView collection = new PagedCollectionView(list);
collection.GroupDescriptions.Add(new PropertyGroupDescription(**???**));
this.MyDataGrid.ItemsSource = collection;
}
but I don't know what my PropertyGroupDescription should be.
Thank you in advance
Add properties called Year, Month and Week and base them on your date field:
public int Year
{
get { return myDate.Year; }
}
Then group by Year, Month, Week :)

Resources