上一篇講了Java的日期與時間Date類別的基礎,這一篇來看看SimpleDateFormat類別。
正如SimpleDateFormat類別的名字所表示,它是用來對日期進行基本的格式化。請看以下的例子:
import java.util.*;
import java.text.*;
public class DateDemo {
public static void main(String args[]) {
Date dNow = new Date( );
SimpleDateFormat ft =
new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
System.out.println("Current Date: " + ft.format(dNow));
}
}
輸出如下:
Current Date: Sun 2014.10.11 at 04:14:09 PM PDT
在這個例子裡SimpleDateFormat類別對當前日期進行格式化。可以看到雖然它叫simple,但其實滿強大的,除了一般的時間日期元素之外,還能直接插入文字(用單引號)。
以下是SimpleDateFormat類別的各種代號解釋:
Character Description Example
G Era designator AD
y Year in four digits 2001
M Month in year July or 07
d Day in month 10
h Hour in A.M./P.M. (1~12) 12
H Hour in day (0~23) 22
m Minute in hour 30
s Second in minute 55
S Millisecond 234
E Day in week Tuesday
D Day in year 360
F Day of week in month 2 (second Wed. in July)
w Week in year 40
W Week in month 1
a A.M./P.M. marker PM
k Hour in day (1~24) 24
K Hour in A.M./P.M. (0~11) 10
z Time zone Eastern Standard Time
' Escape for text Delimiter
" Single quote `