A while back I implemented a report system in a project I was working on where you would send a server two dates (a ‘from date’ and a ‘to date’) and it will return results between those two dates. Well yesterday I had to extend that report system for monthly reports so I figured a drop-down menu with month selection is more convenient to the user than forcing him to manually set the dates from the first of the month to the last of that same month. So I created the drop-down menu, populated it with 12 month entries and moved on to program the logic behind the change handler. This is where I ran into a small problem.
You see, under normal circumstances when working with Java I would use the Java.Util.Calendar class for this, but unfortunately this class is not emulated in GWT (not yet at least). There is a slightly less powerful class that does calendar manipulations though, and is found under com.google.gwt.user.datepicker.client.CalendarUtil. So I figured I’ll use this. I took a quick look at the methods it offers and I wrote a quick and dirty way to get the last day of a certain month.
Here it is:
DateTimeFormat fmt = DateTimeFormat.getFormat("dd.MM.yyyy");
Date date = new Date();
So what I’m basically doing is this:
- First taking the current date by creating a new date object.
- Then I set the date to the first of the month and the month to the selected month from the drop-down list. (be advised here that the month starts from 0 and not 1, i.e. January = 0 and December = 11)
- I use that date to set the ‘date from’ field. This will represent the first of the month of the current year. (you can also change the year if you need to, just be sure to subtract 1900 when using
date.setYear(desiredYear - 1900))
- Then I set the month to the current month + 1 which moves me into the next month.
- Now this is where the CalendarUtil class comes into play.
CalendarUtil.setToFirstDayOfMonth(date);sets the date of the date object to the first of the selected month which in this case means the first of the next month.
- And now
CalendarUtil.addDaysToDate(date, -1);adds the specified number of days to the date. Since I have -1 specified it will actually subtract 1 from the date which means it will move from the first of the next month to the last of the currently selected month.
- Then I just set that date in the ‘date to’ field and make my server call.
- That’s it!
I hope this helps someone facing the same issue. If you have a better, more elegant solution write a comment and I’ll update the post with it.
Thanks for reading!