@TOC
简介
在 Java 8中,添加了新的时间工具包 java.time
- LocalDate
- LocalTime
- LocalDateTime
下面我们以 LocalDate为示例,说明它的操作方法
1. 获取时间
//获取当前时间(日期) 2019-12-08
LocalDate nowDate = LocalDate.now();
//自定义日期 2008-06-01
LocalDate ofDate = LocalDate.of(2008,6,1);
2. 修改时间
LocalDate, LocalTime, LocalDateTime 都是不可变对象,所以修改的时候都是返回一个新的对象,跟String类似
/** 加减时间 **/
//2019-12-09
nowDate.plusDays(1);
//15天前, 2019-11-23
nowDate.plus(-15, ChronoUnit.DAYS);
//2天前
nowDate.minusDays(2);
/** with函数设定时间参数 **/
//当月14号
nowDate.withDayOfMonth(14);
//2020年
nowDate.nowDatewithYear(2020);
3. 时间计算
//时间相距
nowDate.until(nextYear, ChronoUnit.MONTHS);
nowDate.until(nextYear, ChronoUnit.DAYS);
4. 格式化输出
//设置输出格式
DateTimeFormatter dtfm1 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
DateTimeFormatter dtfm2 = DateTimeFormatter.ofPattern("yyyy/MM/dd");
//输出对应字符串
// 2019-12-08
nowDate.format(dtfm1);
// 2019/12/08
nowDate.format(dtfm2);
网友评论