Printing Date/Time in a Given Format
Java contains formatting classes that can be used to format a date into a desired format. The most commonly used class for formatting dates is the SimpleDateFormat class. This class takes a format string as input to its constructor and returns a format object that can then be used to format Date objects. Calling the format() method of the SimpleDateFormat object will return a string that contains the formatted representation of the Date that is passed into the method as a parameter. The output of the phrase shown will be the following: Today's Date and Time is: Mon, 27 Feb 2006 11:18:33 The formatting string passed to the SimpleDateFormat constructor can be a bit cryptic to read if you don't know the formatting codes to use. Table 5.1 shows the formatting codes that can be passed into the SimpleDateFormat constructor. In our phrase, we used the following formatting string: "EEE, dd MMM yyyy HH:mm:ss"
Referring to Table 5.1, let's break down this format string to understand what we are asking for. EEE = 3 character representation of the day of the week. (i.e. Tue) , = puts a comma in the output. dd = 2 character representation of the day of the month. (i.e. 1 31) MMM = 3 character representation of the month of the year. (i.e. Feb) yyyy = 4 digit year string. (i.e. 2006) HH:mm:ss = The hour minute and seconds separated by semi-colons. (i.e. 11:18:33) When we put this all together, we get the date string of Mon, 27 Feb 2006 11:18:33 In addition to creating your own date formatting strings, you can use one of several predefined format strings by using the getTimeInstance(), getdateInstance(), or geTDateTimeInstance() methods of the DateFormat class. For example, the following code will return a formatter object that will use a date format for your default locale: DateFormat df = DateFormat.getDateInstance(); The df formatter can then be used in the same way we used the SimpleDateFormat object in the phrase. See the JavaDoc available for the DateFormat class for a complete discussion of the available standard date/time formatting objects at http://java.sun.com/j2se/1.5.0/docs/api/java/text/DateFormat.html. |