DateFormat的作用:
把时间对象转化成指定格式的字符串,反之把指定格式的字符串转化为时间对象。
DateFormat是一个抽象类,一般使用它的子类SimpleDateFormat类来实现。
DateFormat类和SimpleDateFormat类的使用:
/**
* 测试:字符串和时间对象的互相转换
* 通过使用SimpleDateFormat类。
*/
import sun.awt.im.SimpleInputMethodWindow;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 测试;字符串和Date对象的互相转化
* 使用DateFormat.SimpleDateFormat
*/
public class DateFormat {
public static void main(String[] args) throws ParseException {
// new 一个SimpleDateFormat对象:
SimpleDateFormat s1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
SimpleDateFormat s2 = new SimpleDateFormat("yyyy-MM-dd");
// 将时间对象转为字符串
String daytime = s1.format(new Date());
System.out.println(daytime);
System.out.println(s2.format(new Date()));
System.out.println(new SimpleDateFormat("hh:mm:ss").format(new Date()));
System.out.println(new SimpleDateFormat("yyyy年 第ww周 EE").format(new Date()));
System.out.println(new SimpleDateFormat("yyy年MM月第WW周EE").format(new Date()));
System.out.println(new SimpleDateFormat("今天是今年第D天").format(new Date()));
// 将指定字符串转化为时间对象,字符串需要和指定格式一致
String time = "2030-3-4";
Date date = s2.parse(time);
System.out.println("dat1 :"+date);
time = "2030-3-4 13:24:22";
date = s1.parse(time);
System.out.println("date2 :"+date);
}
}
运行结果:
2021-06-18 04:32:06
2021-06-18
04:32:06
2021年 第25周 星期五
2021年06月第03周星期五
今天是今年第169天
dat1 :Mon Mar 04 00:00:00 CST 2030
date2 :Mon Mar 04 13:24:22 CST 2030
代码中的格式化字符的具体含义见表:
字母 |
日期或时间元素 |
表示 |
示例 |
G |
Era 标志符 |
Text |
AD |
y |
年 |
Year |
1996; 96 |
M |
年中的月份 |
Month |
July; Jul; 07 |
w |
年中的周数 |
Number |
27 |
W |
月份中的周数 |
Number |
2 |
D |
年中的天数 |
Number |
189 |
d |
月份中的天数 |
Number |
10 |
F |
月份中的星期 |
Number |
2 |
E |
星期中的天数 |
Text |
Tuesday; Tue |
a |
Am/pm 标 记 |
Text |
PM |
H |
一天中的小时数(0-23) |
Number |
0 |
k |
一天中的小时数(1-24) |
Number |
24 |
K |
am/pm 中的小时数(0-11) |
Number |
0 |
h |
am/pm 中的小时数(1-12) |
Number |
12 |
m |
小时中的分钟数 |
Number |
30 |
s |
分钟中的秒数 |
Number |
55 |
S |
毫秒数 |
Number |
978 |
z |
时区 |
General time zone |
Pacific Standard Time; PST; GMT-08:00 |
Z |
时区 |
RFC 822 time zone |
0800 |