If you're working with times and dates, you'll often find it necessary to convert between java Date and Calendar objects. Fortunately, as shown in the phrase, this is a very simple thing to do. A Calendar object has a setTime() method that takes a java.util.Date object as a parameter and sets the Calendar object to the date and time contained in the Date object passed in. To convert in the opposite direction, you can use the getTime() method of the Calendar class, which returns the date and time of the calendar as a java.util.Date object. In most Java applications, you'll find uses of both the Date and Calendar classes; thus knowing how to convert from one to the other is something you want to be familiar with. I'd recommend that you create utility methods to perform these conversions so that you can convert from any place in your code with a simple method call. For example, below we show simple methods for converting from a Calendar to a Date class, and a Date to a Calendar class: public static Date calToDate(Calendar cal) { return cal.getTime(); } public static Calendar dateToCal(Date date) { Calendar myCal = Calendar.getInstance(); myCal.setTime(date); return myCal; } |