Class 1, Part 2 | Intro to Java 30-IT-396 |
getTime() and setTime(Date date) methods
class GregorianCalendar has two methods that are particularly handy for dealing with Date objects.
public void method1() {
// Note, the year, month, and day would normally
not be static numbers.
// This is for demonstration purposes only.
GregorianCalendar modifiedDate = new GregorianCalendar(2001,
9, 10);
// perhaps some other code here...
object2.method2(modifiedDate.getTime());
}
// For purposes of demonstration, let's assume this is in an object
named object2.
// Note that this method accepts a Date object, not a GregorianCalendar
object.
public void method2(Date date) {
// make a new GregorianCalendar object.
GregorianCalendar displayDate = new GregorianCalendar();
// Basically, assign the date from the input
to this GregorianCalendar object.
displayDate.setTime(date);
// Now, get the desired variables and print them
out.
int day = displayDate.get(Calendar.DATE);
// Don't forget, Java starts counting months
at 0.
int month = displayDate.get(Calendar.MONTH)
+ 1;
int year = displayDate.get(Calendar.YEAR);
// Print an informational message to the user.
System.out.println("The last modified date is:
" + month + "/" + day + "/" + year);
// And there you have it.
}
Created by: Brandan
Jones January 4, 2002