日期和时间类&比较器
jdk8之前的时间类
一 SimpleDateFormat 简单的日期格式化
-
两个操作
- 格式化:日期——>字符串
- 解析 :格式化的逆过程 字符串——>日期
-
SimpleDateFormat的实例化过程
@Test public void testSimpleDateFormat() throws ParseException { //实例化SimpleDateFormat SimpleDateFormat sdf = new SimpleDateFormat(); //格式化:日期--》字符串 Date date = new Date(); System.out.println(date);//Thu Apr 29 10:02:33 CST 2021 String format=sdf.format(date); System.out.println(format);//2021/4/29 上午9:59 //解析:格式化的逆过程,字符串-->日期 String str="2019-08-09"; // sdf.parse(str);//这里会抛异常,需要设置格式化的格式 //默认的情况是可以的 System.out.println(sdf.parse(format));//Thu Apr 29 10:09:00 CST 2021 //格式指定: SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy.MM.dd hh:mm "); System.out.println(sdf1.format(date));//2021.04.29 10:17 SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy" + "年" + "MM" + "月" + "dd" + "日" + " hh:mm"); System.out.println(sdf2.format(date));//2021年04月29日10:20 String s1="2021年07月28日 10:21"; System.out.println(sdf2.parse(s1));//Wed Jul 28 10:21:00 CST 2021 }
例题:求日期差
@Test
public void test1() throws ParseException {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
String s1="2021.4.29";
String s2="2021.4.25";
long time = sdf.parse(s1).getTime();
long time1 = sdf.parse(s2).getTime();
System.out.println((time - time1) / (1000 * 60 * 60 * 24)+1);
//5