1 package day4.haifei02;
2
3 import java.text.ParseException;
4 import java.util.Date;
5
6 /*
7 2.3 案例-日期工具类
8 把日期转换为指定格式的字符串
9 把字符串解析为指定格式的日期
10 */
11 public class DateUtilsDemo {
12 public static void main(String[] args) throws ParseException {
13 Date d = new Date();
14 String s1 = DateUtils.dateToString(d, "yyyy年MM月dd日 HH:mm:ss");
15 System.out.println(s1);
16 String s2 = DateUtils.dateToString(d , "yyyy-MM-dd");
17 System.out.println(s2);
18 String s3 = DateUtils.dateToString(d, "HH时mm分ss秒");
19 System.out.println(s3);
20
21 String ss = "2021/05/02 12:12:12";
22 Date d1 = DateUtils.stringToDate(ss, "yyyy/MM/dd HH:mm:ss"); //注意要抛出异常不然error
23 System.out.println(d1); //Sun May 02 12:12:12 CST 2021
24 }
25 }
1 package day4.haifei02;
2
3 import java.text.ParseException;
4 import java.text.SimpleDateFormat;
5 import java.util.Date;
6
7 /*
8 工具类特点:构造方法私有+成员方法静态
9 */
10 public class DateUtils {
11
12 private DateUtils(){} //防止外界创建该类的对象
13
14 /*
15 功能:把日期转为指定格式的字符串
16 返回值类型:String
17 参数:Date date, String format
18 */
19 public static String dateToString(Date date, String format){
20 SimpleDateFormat sdf = new SimpleDateFormat(format);
21 String s = sdf.format(date);
22 return s;
23 }
24
25 /*
26 功能:把字符串解析为指定格式的日期
27 返回值类型:Date
28 参数:String s, String format
29 */
30 public static Date stringToDate(String s, String format) throws ParseException {
31 SimpleDateFormat sdf = new SimpleDateFormat(format);
32 Date d = sdf.parse(s); //注意要抛出异常不然error
33 return d;
34 }
35
36 }