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) + " " + simpleDf2.format(today)); 14 } 15 }
运行结果: