Class HighLite Calendar
I think that date manipulation in Java should be easier than it is. For example, there are two date classes in the JDK Standard Edition, one for sql and the util version. Another issue that I have with dates in Java is that the util Date class has about half of it’s methods deprecated. The only useful methods in the Date class which are not deprecated are the get/setTime method. The before and after methods are just convenience methods. On top of multiple date classes and deprecated methods, dates should be considered harmful without a properly localized calendar. Oh, yeah, JDK comes with two flavors of calendars.
It can safely be said that the util Date class is just a wrapper for a long and because of this you can use the Java util Calendar class instead. The Calendar class is an abstract class so you create a calendar instance as follows.
Calendar cal = Calendar.getInstance();
Date now = cal.getTime();
As you can gather from the above code, the calendar is initialized with the current time for your time zone. The static getInstance method is overloaded to accept a locale, a time zone, or both. The calendar is plain simple and I most often use it to get/set the day of a calendar. Here is the code that does just that, I’ll set the day to the the beginning of the month.
The first parameter of the set method in an integer value that represents the field you want to update. You can can change the year by using Calendar.YEAR or the month by using Calendar.MONTH. Once you have the correct date in the calendar instance, you can query for the hour by using the get method as demonstrated in the following snippet of code.
int hour = cal.get(Calendar.HOUR);
With a calendar instance you can easily figure out how many days are in a given month.
int days_in_month = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
You can also add five days, or subtract five minutes, to a calendar object with code similar to the following.
This is part of the Class HighLite Series, which intends to highlight some interesting code and classes available from the JDK.