我们经常需要把时间进行格式化处理,然后在进行存储;同时取出字符串格式的时间并解析成日期,方便阅读。
SimpleDateFormat 类
SimpleDateFormat 类在 java.text.SimpleDateFormat 包下。SimpleDateFormat 通过new来创建一个对象来操作日期对象,然后再丢弃这个对象,大量的对象就这样被创建出来,占用大量的内存和 jvm空间。同时是 SimpleDateFormat 类是线程不安全的。
- 日期转字符串示例:format
输出:Date date = new Date(); System.out.println(date); SimpleDateFormat simpleDateFormat = new SimpleDateFormat(); String stringDate = simpleDateFormat.format(date); System.out.println("日期转字符串:"+stringDate); SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd"); String stringDate1 = simpleDateFormat1.format(date); System.out.println("日期转字符串:"+stringDate1); SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); String stringDate2=simpleDateFormat2.format(date); System.out.println("日期转字符串:"+stringDate2);
Sun Oct 16 09:19:35 CST 2022 日期转字符串:22-10-16 上午9:19 日期转字符串:2022-10-16 日期转字符串:2022-10-16 09:19:35
- 字符串转日期示例:parse
输出:Date date = new Date(); System.out.println(date); SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); String format1 = simpleDateFormat1.format(date); System.out.println("日期转字符串:"+format1); SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd"); String format2 = simpleDateFormat2.format(date); System.out.println("日期转字符串:"+format2); //解析:要求字符串必须是符合 SimpleDateFormat 识别的格式(通过构造器参数来体现),否则会抛异常 Date date1= null; Date date3= null; try { date1 = simpleDateFormat1.parse(format1); date3 = simpleDateFormat2.parse(format2); } catch (ParseException e) { throw new RuntimeException(e); } System.out.println("字符串转日期:"+date1); System.out.println("字符串转日期:"+date3);
Sun Oct 16 09:34:54 CST 2022 日期转字符串:2022-10-16 09:34:54 日期转字符串:2022-10-16 字符串转日期:Sun Oct 16 09:34:54 CST 2022 字符串转日期:Sun Oct 16 00:00:00 CST 2022
DateFormatUtils 和 DateUtils 类
DateFormatUtils、DateUtils(用 org.apache.commons.lang3 中的),他们是线程安全的。可以用来替换 SimpleDateFormat。
DateFormatUtils 类是将日期转换成字符,DateFormatUtils 的 format() 系列方法对应于 SimpleDateFormat 的 format() 的方法。
public static java.lang.String format (java.util.Date date, java.lang.String pattern)
DateUtils 类是将字符串转换成日期。DateUtils 的 parseDate() 系列方法对应于 SimpleDateFormat 的 parse() 的方法。
public static java.util.Date parseDate (java.lang.String str, java.lang.String[] parsePatterns) throws java.text.ParseException
public static java.util.Date parseDateStrictly (java.lang.String str, java.lang.String[] parsePatterns)
- 转换示例:
输出:Date date = new Date(); System.out.println(date); // DateFormatUtils.format() 类似 simpledateformat.format() 方法 String format = DateFormatUtils.format(date, "yyyy-MM-dd hh:mm:ss"); System.out.println("日期转字符串:" + format); // DateUtils.parseDateStrictly() 类似 simpledateformat.format() 方法 try { Date date1 = DateUtils.parseDateStrictly(format, "yyyy-MM-dd hh:mm:ss"); System.out.println("字符串转日期:" + date1); } catch (ParseException e) { throw new RuntimeException(e); }
Sun Oct 16 10:22:59 CST 2022 日期转字符串:2022-10-16 10:22:59 字符串转日期:Sun Oct 16 10:22:59 CST 2022