Java 8新增的日期、时间格式器
来源:互联网 发布:苹果打击垫软件 编辑:程序博客网 时间:2024/06/05 02:05
一 获取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
- Java 8新增的日期、时间格式器
- Java 8新增的日期、时间格式器
- java8新增的日期,时间包以及格式器
- Java 8新增日期时间新成员
- Java日期时间格式
- java日期时间格式
- Java日期时间格式
- Java时间日期格式
- Java时间日期格式的转换
- Java时间日期格式转换
- Java时间日期格式转换
- Java时间日期格式转换
- Java时间日期格式转换
- Java时间日期格式转换
- JAVA时间日期格式转换
- Java时间日期格式转换
- Java 时间日期格式转换
- Java时间日期格式转换
- 超类对象引用变量引用子类对象
- mybatis generator 自定义类名(修改mybatis-generator-1.3.2源码改dao类名)
- Gym 100685G Gadget Hackwrench (LCA)
- RxJava 各种操作符(2)
- js播放不了多段语音
- Java 8新增的日期、时间格式器
- MySQL5.6生产库自动化安装部署
- 每天一条linux--whereis
- 你必须知道的C语言问题
- Android 6 权限 详解
- java对象序列化与反序列化
- 实验二-输出希腊字母表
- PHP数组键值使用单引号和双引号和无符号的区别
- Android自定义控件:动画类(十二)----layoutAnimation与gridLayoutAnimation