SimpleDateFormat
是一个以与语言环境有关的方式来格式化和解析日期的具体类。它允许进行格式化(日期 -> 文本)、解析(文本 -> 日期)和规范化。
字母 | 日期或时间元素 | 表示 | 示例 |
G | Era 标志符 | AD | |
y | 年 | 1996; 96 | |
M | 年中的月份 | July; Jul; 07 | |
w | 年中的周数 | 27 | |
W | 月份中的周数 | 2 | |
D | 年中的天数 | 189 | |
d | 月份中的天数 | 10 | |
F | 月份中的星期 | 2 | |
E | 星期中的天数 | Tuesday; Tue | |
a | Am/pm 标记 | PM | |
H | 一天中的小时数(0-23) | 0 | |
k | 一天中的小时数(1-24) | 24 | |
K | am/pm 中的小时数(0-11) | 0 | |
h | am/pm 中的小时数(1-12) | 12 | |
m | 小时中的分钟数 | 30 | |
s | 分钟中的秒数 | 55 | |
S | 毫秒数 | 978 | |
z | 时区 | Pacific Standard Time; PST; GMT-08:00 | |
Z | 时区 | -0800 |
SimpleDateFormat函数的继承关系:
java.lang.Object
|
+----java.text.Format
|
+----java.text.DateFormat
|
+----java.text.SimpleDateFormat
举例
importjava.text.SimpleDateFormat;
importjava.util.Date;
publicclass SimpleDateformat {
publicstatic void main(String[] args) {
SimpleDateFormat sy=new SimpleDateFormat("yyyy");
SimpleDateFormat sm=new SimpleDateFormat("MM");
SimpleDateFormat sd=new SimpleDateFormat("dd");
SimpleDateFormat ymd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String syear=sy.format(date);
String smon=sm.format(date);
String sday=sd.format(date);
String symd=ymd.format(date);
System.out.println(syear);
System.out.println(smon);
System.out.println(sday);
System.out.println(symd);
}
}
结果:
2013
03
24
2013-03-2416:42:04