public class DateTimeTest1 {
/*
SimpleDateFormat的使用: SimpleDateFormat对日期Date类的格式化和解析
1. 两个操作:
1.1 格式化:日期 ---> 字符串
1.2 解析:格式化的逆过程,字符串 ---> 日期
2.SimpleDateFormat的实例化
*/
@Test
public void testSimpleDateFormat() throws ParseException {
//实例化SimpleDateFormat:使用默认的构造器
SimpleDateFormat sdf = new SimpleDateFormat();
//格式化:日期 ---> 字符串
Date date = new Date();
System.out.println(date);//Mon Apr 25 09:04:54 CST 2022
String format = sdf.format(date);
System.out.println(format);//2022/4/25 上午9:04
//解析:格式化的逆过程,字符串 ---> 日期
String str = "2022/4/25 上午9:08";
Date date1 = sdf.parse(str);
System.out.println(date1);
//************按照指定的方式格式化和解析:调用带参的构造器*************************
// SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy.MMMMM.dd GGG hh:mm aaa");
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//格式化
String format1 = sdf1.format(date);
System.out.println(format1);//2022-04-25 09:18:38
//解析:要求字符串必须是符合SimpleDateFormat识别的格式(通过构造器参数体现)
//否则就会抛异常
Date date2 = sdf1.parse(format1);
System.out.println(date2);
}
/*
练习一:字符串"2020-09-08"转换为java.sql.Date
*/
@Test
public void testExer() throws ParseException {
String birth = "2020-09-08";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf1.parse(birth);
System.out.println(date);
java.sql.Date birthDate = new java.sql.Date(date.getTime());
System.out.println(birthDate);
}
/*
练习二:"三天打渔两天晒网" 1990-01-01 xxxx-xx-xx 打渔or晒网?
举例:2020-09-08 ? 总天数
总天数 % 5 == 1,2,3 :打渔
总天数 % 5 == 4,0 :晒网
总天数的计算?
方式一:date2.getTime() - date1.getTime() / (1000 * 60 * 60 * 24) + 1
方式二:1990-01-01 ---> 2019-12-31 + 2020-01-01 ---> 2020-09-08
*/
}
[常用类]SimpleDateFormat的使用
最新推荐文章于 2023-07-14 08:49:04 发布