Sunday, March 27, 2011

Formatting Date objects

I'm creating dates for my assessment - storing the start date and end date for a contractor's employment.

To print out the date, must use the SimpleDateFormat class, which will format the date to make it more readable.


public String toString()
{
SimpleDateFormat dF = new SimpleDateFormat("dd/MM/yyyy");
String theEnrolledDate = dF.format(enrolledDate);

return super.toString()
+ "/nEnrolled Date: " + theEnrolledDate
}

I've been having some issues with passing a date into a constructor, but I re-read an email from my tutor and it makes sense now (thanks Eddie!)

Constructor:


public Student(Date enrolledDate)
{
this.name = null;
this.id = idCounter++;
this.enrolledDate= enrolledDate;
}


Creating an instance of Student:
Student s1 = new Student(new GregorianCalendar(2011, 0, 3).getTime());


Just need to put the dates in, and remember that month is counted from 0, not 1.

UPDATE
Make sure that the values are initilised. SimpleDateFormat does not work when the date is null. It spits exceptions that don't make sense.....

In other news, wine is helping me with my coding. Lets just hope I don't go over Ballmer's Peak. Where's a breathalyser when I need one?

No comments:

Post a Comment