JCalendar sets to March 30 when February is chosen - calendar

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);

Related

Guys I don't understand how to write tests

I have a class in which I get the number of ids per year with a soql query on a custom object:
public static Integer numberRecords(Integer year) {
List<AggregateResult> numbersOfRecords = [
SELECT Keeper__c
FROM Month_Expense_Application__c
WHERE calendar_year(MonthDate__c) =: year
];
Set<Id> keepers = new Set<Id>();
for (AggregateResult result : numbersOfRecords) {
keepers.add((Id)result.get('Keeper__c'));
}
Integer value = keepers.size();
return value;
}
I'm trying to write a test for this method by creating an object and filling in the fields it needs, then I try to get the id with a soql request and compare:
#isTest
public class ExpenseAdminControllerTests {
#isTest
public static void numberRecordsTests() {
Month_Expense_Application__c monthExpenseTest = new Month_Expense_Application__c(
Balance__c = 12.3,
Income__c = 11,
Keeper__c = '0034x00001K7kGCAAZ',
MonthDate__c = date.newInstance(2022, 11, 21)
);
Integer year = 2022;
List<Month_Expense_Application__c> numbersOfRecords = [
SELECT Keeper__c
FROM Month_Expense_Application__c
WHERE calendar_year(MonthDate__c) =: year AND Id =: monthExpenseTest.Id
];
Set<Id> keepers = new Set<Id>();
keepers.add(numbersOfRecords[0].Keeper__c);
Integer value = keepers.size();
System.assertEquals(1, value);
}
}
But i cant tell me what am i doing wrong
I guess you just forgot to insert "monthExpenseTest" in actual database, by means that you have just created a object by using below lines as you mentioned
Month_Expense_Application__c monthExpenseTest = new Month_Expense_Application__c(
Balance__c = 12.3,
Income__c = 11,
Keeper__c = '0034x00001K7kGCAAZ',
MonthDate__c = date.newInstance(2022, 11, 21)
);
by writing above lines you just created object which is present in memory only. it is not stored in database, so that it is not fetched when you try to fetch it via SOQL Query.
Now you may want to add one more line after above code.which is given as below
insert monthExpenseTest ;
so after inserting your object is stored in database. now you can fetch it via SOQL query.
So your test class will be looks like below
#isTest
public class ExpenseAdminControllerTests {
#isTest
public static void numberRecordsTests() {
Month_Expense_Application__c monthExpenseTest = new Month_Expense_Application__c(
Balance__c = 12.3,
Income__c = 11,
Keeper__c = '0034x00001K7kGCAAZ',
MonthDate__c = date.newInstance(2022, 11, 21)
);
insert monthExpenseTest;
Integer year = 2022;
Integer keepers = ExpenseAdminController.numberRecords(year);
System.assertEquals(1, keepers);
}
}
So when you are testing ExpenseAdminController then you just need to call that method because you want to test it. in test class which is mentioned in question it not testing numberRecords() method instead of you are rewriting logic.

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)

Avoiding picking up future dates in Calendar Codename One

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();
}

How to black out specific days of the week (datepicker) [VB]

I was wondering if it is possible to make particular days unavailable from the calendar (DatePicker), more specifically every Monday and Tuesday. I have found similar threads (How do create a DatePicker with only Sundays enabled? and Disable specific days of the week on jQuery UI datepicker) about blacking out dates, however, I have not been able to modify their code for my specific goal. I'm writing this application in VB.NET (WPF).
The functions I used so far, for blacking out dates are:
Datepicker1.BlackoutDates.AddDatesInPast()
Datepicker2.BlackoutDates.Add(New CalendarDateRange(DateTime.Now.AddDays(1), DateTime.MaxValue))
Where the first function will blackout the past-dates, and the second will black out all future dates. Because there is a 'DateRange' required for the second function, I'm not able to alter this function for my need.
Thanks in advance
Jerry
I modified one of the examples and came up with this.
It worked for me.
private void MyDatePicker_CalendarOpened(object sender, RoutedEventArgs e)
{
MyDatePicker.DisplayDateStart = DateTime.Now;
MyDatePicker.DisplayDateEnd = DateTime.Now + TimeSpan.FromDays(1000);
var minDate = MyDatePicker.DisplayDateStart ?? DateTime.MinValue;
var maxDate = MyDatePicker.DisplayDateEnd ?? DateTime.MaxValue;
for (var d = minDate; d <= maxDate && DateTime.MaxValue > d; d = d.AddDays(1))
{
if (d.DayOfWeek == DayOfWeek.Monday || d.DayOfWeek == DayOfWeek.Tuesday)
{
MyDatePicker.BlackoutDates.Add(new CalendarDateRange(d));
}
}
}
And here's a bonus: Prevent Certain Dates from Being Selected.
Thank you Okuma Scott, that was some helpful feedback! I rewrote your bit of code to VB language and according to my specific needs.
The included code will check all days in the next year, and will black out all the Mondays and Tuesdays.
Private Sub Datepicker_CalendarOpened(sender As Object, e As RoutedEventArgs) Handles Datepicker.CalendarOpened
Dim currDate As Date = DateTime.Now
Dim maxDate As Date = DateTime.Now.AddDays(356)
While (currDate < maxDate)
If currDate.DayOfWeek = DayOfWeek.Monday Or currDate.DayOfWeek = DayOfWeek.Tuesday Then
DatumSelectie.BlackoutDates.Add(New CalendarDateRange(currDate))
End If
currDate = currDate.AddDays(1)
End While
End Sub

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