Recipe 6.2 Printing DateTime in a Given Format


Recipe 6.2 Printing Date/Time in a Given Format

Problem

You want to print the date and/or time in a locale-sensitive or otherwise-specified format.

Solution

Use java.text.DateFormat.

Discussion

To print the date in the correct format for whatever locale your software lands in, simply use the default DateFormat formatter, which is obtained by calling DateFormat.getInstance( ) :

import java.util.*; import java.text.*; public class DateFormatBest {         public static void main(String[] args) {                 Date today = new Date( );                 DateFormat df = DateFormat.getInstance( );                 System.out.println(df.format(today));                 DateFormat df_fr =                          DateFormat.getDateInstance(DateFormat.FULL, Locale.FRENCH);                 System.out.println(df_fr.format(today));         } }

When I run this, it prints:

3/3/04 12:17 PM mercredi 3 mars 2004

You can ask for a default date and time formatter (df in the example), or a TimeFormatter or DateFormatter that extracts just the time or date portion of the Date object (df_fr in the example). You can also request a nondefault Locale (df_fr in the example). Five codes FULL, LONG, MEDIUM, SHORT and DEFAULT can be passed to describe how verbose a format you want.

Suppose you want the date printed, but instead of the default format, you want it printed like "Sun 2004.07.18 at 04:14:09 PM PDT". A look at the Javadoc page for SimpleDateFormat the only nonabstract subclass of DateFormat reveals that it has a rich language for specifying date and time formatting. Be aware that in so doing you are presuming to know the correct format in all locales; see Chapter 15 for why this may be a bad idea.

To use a default format, of course, we can just use the Date object's toString( ) method, and for a localized default format, we use DateFormat.getInstance( ). But to have full control and get the "Sun 2004.07.18 at 04:14:09 PM PDT", we construct an instance explicitly, like so:

new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");

E means the day of the week; yyyy, MM, and dd are obviously year, month, and day. The quoted string 'at' means the string "at". hh:mm:ss is the time; a means A.M. or P.M., and zzz means the time zone. Some of these are more memorable than others; I find the zzz tends to put me to sleep. Here's the code:

// DateDemo.java  Date dNow = new Date( );    /* Simple, Java 1.0 date printing */  System.out.println("It is now " + dNow.toString( ));    // Use a SimpleDateFormat to print the date our way.  SimpleDateFormat formatter      = new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");  System.out.println("It is " + formatter.format(dNow));

There are many format symbols; a list is shown in Table 6-1.

Table 6-1. Simple DateFormat format codes

Symbol

Meaning

Presentation

Example

G

Era designator

Text

AD

y

Year

Number

2001

M

Month in year

Text and Number

July or 07

d

Day in month

Number

10

h

Hour in A.M./P.M. (1~12)

Number

12

H

Hour in day (0~23)

Number

0

m

Minute in hour

Number

30

s

Second in minute

Number

43

S

Millisecond

Number

234

E

Day in week

Text

Tuesday

D

Day in year

Number

360

F

Day of week in month

Number

2 (second Wed. in July)

w

Week in year

Number

40

W

Week in month

Number

1

a

A.M./P.M. marker

Text

PM

k

Hour in day (1~24)

Number

24

K

Hour in A.M./P.M. (0~11)

Number

0

z

Time zone

Text

Eastern Standard Time

'

Escape for text

Delimiter

 

"

Single quote

Literal

`


You can use as many of the given symbols as needed. Where a format can be used either in text or numeric context, you can set it to a longer form by repetitions of the character. For codes marked Text, four or more pattern letters cause the formatter to use the long form; fewer cause it to use the short or abbreviated form if one exists. Thus, E might yield Mon, whereas EEEE would yield Monday. For those marked Number, the number of repetitions of the symbol gives the minimum number of digits. Shorter numbers are zero-padded to the given number of digits. The year is handled specially: yy yields an ambiguous[2] two-digit year (98, 99, 00, 01 . . . ), whereas yyyy yields a valid year (2001). For those marked Text and Number, three or more symbols causes the formatter to use text, while one or two make it use a number: MM might yield 01, while MMM would yield January.

[2] Remember Y2K? Use a four-digit year!



Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net