Java—格式化日期/时间

DateFormat

   DateFormat继承MessageFormat,是实现日期格式化的抽象类。提供两个方法:format()用于将数值或日期格化式成字符串;parse()方法用于将字符串解析成数值或日期。

parse()用法举例:

String dateStr = "2019-12-10";
System.out.println(DateFormat.getDateInstance().parse(dateStr);

输出结果:

Thur Dec 10 00:00:00 CST 2019

如何得到DateFormat对象?

  1. getDateInstance():返回一个只有日期,无时间的日期格式器;
  2. getImeInstance():返回一个只有时间,没有日期的时间格式器;
  3. getDateTimeInstance():返回一个既有时间、又有日期的格式器。

SimpleDateFormat

   DateFormat在格式化日期时间方面显得不够灵活,需要特定的格式才能解析,为了更好的格式化Date,它的子类SimpleDateFormat出现了。
使用示例:

public class SimpleDateFormatTest{
	public static void main(String[] args) throws ParseException {
		Date date = new Date();
		//创建SimpleDateFormat对象;
		SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("Gyyyy年中第D天");
		// 将date日期解析为字符串
		String dateStr = simpleDateFormat1.format(date);
		System.out.println("公元日期表示: " + dateStr);
		
		String dateStr2 = "19###十二月##10";
		SimpleDateFormat simpleDateFormat2 = SimpleDateFormat("y###MMM##d");
		//将字符串解析成日期
		System.out.println("一般日期为: " + simpleDateFormat2.parse(dateStr2));
	}
}

输出结果:

公元日期表示: 公元2020年中第77天
一般日期为: Thur Dec 10 00:00:00 CST 2019

DateTimeFormatter

   DateTimeFormatter是Java 8 中java.time.format包下新增的格式器类,不仅可以把日期或时间对象格式化成字符串,也可以把特定格式的字符串解析成日期或时间对象。
format()示例

public class DateTimeFormatterFormatTest{
	public static void main(String[] args) {
		
		LocalDateTime localDateTime = LocalDateTime.now();
		
		DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
		System.out.println(dateTimeFormatter.format(localDateTime ));
		System.out.println(localDateTime.format(dateTimeFormatter));
		//全日期时间
		DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL, FormatStyle.MEDIUM);
		System.out.println(dateTimeFormatter2.format(localDateTime ));
		System.out.println(localDateTime.format(dateTimeFormatter2));
		//模式字符串创建格式器
		DateTimeFormatter dateTimeFormatter3 = DateTimeFormatter.ofPattern("Gyyyy-MMM-dd HH:mm:ss");
		System.out.println(dateTimeFormatter3.format(localDateTime ));
		System.out.println(localDateTime.format(dateTimeFormatter3));
	}
}

输出结果

2020-03-17T22:41:20.220
2020-03-17T22:41:20.220
2020317日 星期二 22:41:20
2020317日 星期二 22:41:20
公元2020-三月-17 22:41:20
公元2020-三月-17 22:41:20

parse()示例

public class DateTimeFormatterParseTest{
	public static void main(String[] args) {
		String str = "2020$$$03$$$dd 22时51分10秒"
		DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyy$$$MMM$$$dd HH时mm分ss秒");
		//解析日期
		LocalDateTime localDateTime = LocalDateTime.parse(str, dateTimeFormatter);
		System.out.println(localDateTime);
	}
}

输出结果:

2020-03-17T22:51:10
发布了97 篇原创文章 · 获赞 127 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/Andya_net/article/details/104932631