Java 8新增的日期、时间格式器

来源:互联网 发布:世界城市经纬度数据库 编辑:程序博客网 时间:2024/06/05 08:37

一 获取DateTimeFormatter对象的三种方式

  • 直接使用静态常量创建DateTimeFormatter格式器
  • 使用代码不同风格的枚举值来创建DateTimeFormatter格式器
  • 根据模式字符串来创建DateTimeFormatter格式器

二 DateTimeFormatter完成格式化
1 代码示例

import java.time.*;import java.time.format.*;public class NewFormatterTest{public static void main(String[] args){DateTimeFormatter[] formatters = new DateTimeFormatter[]{// 直接使用常量创建DateTimeFormatter格式器DateTimeFormatter.ISO_LOCAL_DATE,DateTimeFormatter.ISO_LOCAL_TIME,DateTimeFormatter.ISO_LOCAL_DATE_TIME,// 使用本地化的不同风格来创建DateTimeFormatter格式器DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL, FormatStyle.MEDIUM),DateTimeFormatter.ofLocalizedTime(FormatStyle.LONG),// 根据模式字符串来创建DateTimeFormatter格式器DateTimeFormatter.ofPattern("Gyyyy%%MMM%%dd HH:mm:ss")};LocalDateTime date = LocalDateTime.now();// 依次使用不同的格式器对LocalDateTime进行格式化for(int i = 0 ; i < formatters.length ; i++){// 下面两行代码的作用相同System.out.println(date.format(formatters[i]));System.out.println(formatters[i].format(date));}}}

 
2 运行结果

2016-09-04
2016-09-04
12:18:33.557
12:18:33.557
2016-09-04T12:18:33.557
2016-09-04T12:18:33.557
2016年9月4日 星期日 12:18:33
2016年9月4日 星期日 12:18:33
下午12时18分33秒
下午12时18分33秒
公元2016%%九月%%04 12:18:33
公元2016%%九月%%04 12:18:33
3 代码说明

上面代码使用3种方式创建了6个DateTimeFormatter对象,然后程序中使用不同方式来格式化日期。

 

三 DateTimeFormatter解析字符串
1 代码示例

import java.time.*;import java.time.format.*;public class NewFormatterParse{public static void main(String[] args){// 定义一个任意格式的日期时间字符串String str1 = "2014==04==12 01时06分09秒";// 根据需要解析的日期、时间字符串定义解析所用的格式器DateTimeFormatter fomatter1 = DateTimeFormatter.ofPattern("yyyy==MM==dd HH时mm分ss秒");// 执行解析LocalDateTime dt1 = LocalDateTime.parse(str1, fomatter1);System.out.println(dt1); // 输出 2014-04-12T01:06:09// ---下面代码再次解析另一个字符串---String str2 = "2014$$$四月$$$13 20小时";DateTimeFormatter fomatter2 = DateTimeFormatter.ofPattern("yyy$$$MMM$$$dd HH小时");LocalDateTime dt2 = LocalDateTime.parse(str2, fomatter2);System.out.println(dt2); // 输出 2014-04-13T20:00}}

 

2 运行结果

2014-04-12T01:06:09
2014-04-13T20:00

 

3 代码说明

上面代码定义了两个不同格式日期、时间字符串。为了解析他们,代码分别使用对应的格式字符串创建了DateTimeFormatter对象,这样DateTimeFormatter即可按照格式化字符串将日期、时间字符串解析成LocalDateTime对象。

0 0
原创粉丝点击