Java Calendar
The Calendar class is a java utility for obtaining and modifying the current date and time. It contains all the functionality necessary to get the current time in any time zone as well as methods for manipulating the Date.
import java.util.Calendar;
Java SimpleDateFormat
The SimpleDateFormat is another utility that is used to format a Date object into a String based on the supplied format. The SimpleDateFormat object can be used to return the full date and time, date only, the month, or any such combination.
import java.text.SimpleDateFormat
How to use the Calendar utility
The Calendar object is instantiated by using the getInstance method.
Calendar calendar = Calendar.getInstance();
Once you have an instance of the calendar you can obtain the Date by use of the getTime method
calendar.getTime()
It is a common practice of having to modify the Date object to a different time in our applications. This is done by the set and add methods. The add method is used to manipulate a parameter of the Date while the set method is used to set a parameter to a certain value.
For example if we wanted to get yesterdays date we would use the add method and modify the Date by -1.
calendar.add( Calendar.DATE, -1 );
We could also modify the month the same way.
calendar.add( Calendar.MONTH, 1 );
However if we wanted to change the Date to the first of the month we would use the set method
calendar.set( Calendar.DAY_OF_MONTH, 1 );
In addition to the constants above that represent the date, month, and day of month there are others for year, seconds, hours, and etc that can be used to modify the date in any many necessary for your application.
Using the SimpleDateFormat Object to return the Date in readable format.
To return a readable string representation of the Date obtained by the Calendar object the SimpleDateFormat format method is utilized. This method returns a string that represents the inputted date based on the format of the SimpleDateFormat object.
To instantiate the SimpleDateFormat object you call its constructor passing the textual format of the desired output of the date. The format object understands the standard date and time representations of dd, mm, MM, YYYY, yy, and etc. The example below shows how to display the time format as Date/Month/Year.
SimpleDateFormat dateFormat = new SimpleDateFormat( "dd/MM/yy" );
String date = dateFormat.format( calendar.getTime() );
Conclusion
Utilizing the Calendar and SimpleDateFormat objects allows you as a developer to easily obtain and modify the Date without doing custom arithmetic. They can be especially helpful in generating SQL queries for obtaining data for the past month, year, or a range of times.
Comments & Questions
Add Your Comment