`DateTime' example program: an applet that displays that date and time

DateTime.java

// DateTime.java
// This program constructs an applet that shows the current date and time like 
//  this:
// 
//    13:21
//    Sunday, July 14 
// 
// To do this it uses the `Date' and `Calendar' classes to get the hour, minute, 
//  day of week, day of month and month as numbers. The numeric values of
//  month and day-of-week are then used to retrieve the name of the month 
//  and the name of the day from arrays of strings.

// Kevin Boone, June 1999

import java.applet.Applet;
import java.util.Date;
import java.util.GregorianCalendar;
import java.text.DecimalFormat;
import java.awt.*;

public class DateTime extends Applet
{
final String dayNames[] = {"Sunday", "Monday", "Tuesday", "Wednesday", 
				"Thursday", "Friday", "Saturday"};
final String monthNames[] = {"January", "February", "march", "April", 
				"May", "June", "July", "August", 
				"September", "October", 
				"Novemeber", "December"};

public void paint (Graphics g)
	{
	// The `calendar' class contains operations for getting
	//  the day and date from a `Date' object.
	GregorianCalendar calendar = new GregorianCalendar();
	
	// The `setTime' operation sets the time to that contained in the
	//  the specified date object. As a new date object by default
	//  contains the current date and time, the effect of the line
	//  below is to initialize the Calendar obejct to the current
	//  date and time.
 	calendar.setTime (new Date());	

	/// QUESTION: why must we write `calendar.HOUR_OF_DAY' and
	///  not simply `HOUR_OF_DAY'

	// (Note that by convention in Java programming, constants
	//  are given names in capital letters). This is not
	//  compulsory, but all professional Java programmers do it

	int hour = calendar.get(calendar.HOUR_OF_DAY);
	int minute = calendar.get(calendar.MINUTE);

	int dayOfWeek = calendar.get(calendar.DAY_OF_WEEK);
	int dayOfMonth = calendar.get(calendar.DAY_OF_MONTH);
	int month = calendar.get(calendar.MONTH);
	
	/// QUESTION: we have the hour and minute in the variables 
	///  `hour' and `minute'. Why do we need the `DecimalFormat'
	///  class? Why not just convert `hour' and `minute' to
	///  strings directly (using `toString()', as in the previous examples?)

	DecimalFormat twoDigitFormat = new DecimalFormat();
	twoDigitFormat.setMinimumIntegerDigits(2);

	String timeString = twoDigitFormat.format((hour)) 
		+ ":" 
		+ twoDigitFormat.format((minute));
	g.drawString (timeString, 20, 20);

	/// QUESTION: why do week need element `dayOfWeek - 1' in the array,
	///  and not `dayOfWeek' ?

	String dayName = dayNames[dayOfWeek - 1];
	String monthName = monthNames[month];
	
	String dateString = dayName + ", " + monthName + " " + dayOfMonth;
	
	g.drawString (dateString, 20, 40);
	}

}


©1994-2003 Kevin Boone, all rights reserved