Date类
类Date 是java中常用的表示时间的类,它表示特定的时间,精确到毫秒。
日期和时间格式由日期和时间模式字符串指定。A-Z、a-z被解释成模式字母,文本用单引号引起来。
Java中定义了以下模式字母(其他字母都被保留)
G Era标志符 例:AD
y 年
M 年中的月份
w 年中的周数
W 月份中的周数
D 年中的天数
d 月份中的天数
F 月份中的星期
E 星期中的天数
a am/pm标记 例:PM
H 一天中的小时数(0-23)
k 一天中的小时数(1-24)
K am/pm中的小时数(0-11)
h am/pm中的小时数(1-12)
m 小时中的分钟数
s 分钟中的秒数
S 毫秒数
z 时区 例:Pacific Standard Time;PST;GMT-08:00
Z 时区 例:-0800
关于Date类的使用,我们使用SimpleDateFormat类来说明:
SimpleDateFormat使用:
SimpleDateFormat对日期Date类的格式化和解析
1、两个操作:
1.1格式化: 日期 ----> 字符串
1.2解析: 格式化的逆过程,字符串 ----> 日期
2、SimpleDateFormat的实例化
package com.dell.day17;
import org.junit.Test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTimeTest {
@Test
public void TestSimpleDateFormat() throws ParseException {
//实例化SimpleDateFormat:使用默认的构造器(一般不使用)
SimpleDateFormat sdf = new SimpleDateFormat();
//格式化:日期 ----> 字符串
Date date = new Date();
System.out.println(date);
System.out.println("------------------");
String format = sdf.format(date);
System.out.println(format);
System.out.println("------------------");
//解析: 格式化的逆过程,字符串 ----> 日期
String str = "19-12-18 上午11:43";
Date date1 = sdf.parse(str);
System.out.println(date1);
System.out.println("------------------");
//****************按照指定方式格式化和解析:调用带参构造器******************
SimpleDateFormat sdf1 = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");//使用自己构造的
//格式化
String format1 = sdf1.format(date);
System.out.println(format1);//2021-03-29 11:27:43
System.out.println("------------------");
//解析:要求字符串必须是符合SimpleDateFormat识别的格式(通过构造器参数体现)
//否则,会抛异常
Date date2 = sdf1.parse("2021-03-29 11:27:43");
System.out.println(date2);
}
}
输出结果:
总结: 上述内容就是SimpleDateFormat的使用,有些浅显,望多指正。
在今后学习到更多关于Date类的知识时,会进行更新。