SimpleDateFormat
是一个以与语言环境有关的方式来格式化和解析日期的具体类。它允许进行格式化(日期 -> 文本)、解析(文本 -> 日期)和规范化。
构造方法
SimpleDateFormat() 用默认的模式和默认语言环境的日期格式符号构造 SimpleDateFormat 。 |
SimpleDateFormat(String pattern) 用给定的模式和默认语言环境的日期格式符号构造 SimpleDateFormat 。 |
日期格式化方法(Date转String)
1.通过构造方法设置日期格式
public class SimpleDateFormatDemo {
public static void main(String[] args) {
//创建一个日期对象获取当前时间
Date date = new Date();
//通过构造方法来设置格式化日期的格式信息
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//调用format方法对日期进行格式化
String format = simpleDateFormat.format(date);
System.out.println(format);
}
}
打印结果:
2019-07-24 19:58:55
2.通过applyPattern方法设置格式
public class SimpleDateFormatDemo2 {
public static void main(String[] args) {
//创建一个日期对象获取当前时间
Date date = new Date();
//获得simpleDateFormat对象
SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
//通过applyPattern来设置日期格式
simpleDateFormat.applyPattern("yyyy-MM-dd HH:mm:ss");
//调用format方法对日期进行格式化
String format = simpleDateFormat.format(date);
System.out.println(format);
}
}
打印结果:
2019-07-24 19:59:46
日期解析方法(String转Date)
Date parse(String source) 将符合格式的指定字符串转换为Date
public class SimpleDateFormatDemo3 {
public static void main(String[] args) throws ParseException {
//测试的字符串数据
String str1="2019-07-24 19:37:54";
String str2="2019年07月24日 19:37:54";
String str3="2019/07/24 19:37:54";
//给定格式的simpleDateFormat对象
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//通过parse方法解析字符串日期
Date date1 = simpleDateFormat1.parse(str1);
Date date2 = simpleDateFormat2.parse(str2);
Date date3 = simpleDateFormat3.parse(str3);
//打印Date数据
System.out.println(date1);
System.out.println(date2);
System.out.println(date3);
}
}
打印结果:
Wed Jul 24 19:37:54 CST 2019
Wed Jul 24 19:37:54 CST 2019
Wed Jul 24 19:37:54 CST 2019
ps:parse()中引入的日期参数,格式必须与调用该方法的SimpleDateFormat对象封装的格式一致,若不一致会报错
Parse格式写法:
字母 日期或时间元素 表示 示例 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