Date類用於表示時間實例,精確到毫秒。Date類在java.util包中。當生成一個新的Date對象時,將此對象設置為生成它的時間。Date類包括toString方法,此方法將時間的內部格式轉換成字符串表示。
1 import java.util.*; 2 import javax.swing.*; 3 4 class Date_test{ 5 public static void main(String[] args){ 6 Date today; 7 today = new Date(); 8 JOptionPane.showMessageDialog(null, today.toString()); 9 } 10 }
運行結果:
CST代表中部標准時間
如果不喜歡默認格式,可以使用SimpleDateFormat類
Symbol | Meaning | Value | Sample |
y | Year | Number | yyyy-2018 |
M | Month in year | Text or Number | MM-8 MMM-Aug MMMM-August |
d | Day in month | Number | dd-20 |
D | Day in year | Number | DDD-289 |
H | Hour in day(0-23) | Number | HH-17 |
a | AM/PM marker | Text | a-AM |
m | Minutes in hour | Number | mm-35 |
s | Seconds in minute | Number | ss-54 |
S | Millisecond | Number | SSS-897 |
E | Day in week | Text | E-Mon EEEE-Monday |
h | Hour in AM/PM | Number | hh-09 |
1 import java.util.*; 2 import javax.swing.*; 3 import java.text.*; 4 5 class Date_test{ 6 public static void main(String[] args){ 7 Date today; 8 SimpleDateFormat simpleDf1, simpleDf2; 9 10 today = new Date(); 11 simpleDf1 = new SimpleDateFormat(); 12 simpleDf2 = new SimpleDateFormat("hh:mm a MM/dd/yyyy"); 13 JOptionPane.showMessageDialog(null, simpleDf1.format(today) + "\n" + simpleDf2.format(today)); 14 } 15 }
運行結果: