时间调节器
# 时间调节器
调整时间的高级方法
# TemporalAdjusters
LocalDateTime
还有一个通用的 with()
方法允许我们做更复杂的运算。with 的参数是 TemporalAdjuster 对象,是一个时间调节器,将一个时间调节成另外一个时间。我们来看看示例代码:
LocalDateTime dt = LocalDateTime.of(2022,5, 21, 13, 14, 15);
dt = dt.with(TemporalAdjusters.firstDayOfMonth());
System.out.println("firstDayOfMonth: " + dt); //2022-05-01T13:14:15
dt = dt.with(TemporalAdjusters.lastDayOfMonth());
System.out.println("lastDayOfMonth: " + dt); //2022-05-31T13:14:15
dt = dt.with(TemporalAdjusters.next(DayOfWeek.MONDAY)); //找到下一个星期一
System.out.println("DayOfWeek.MONDAY: " + dt); //2022-06-06T13:14:15
dt = dt.with(TemporalAdjusters.firstDayOfNextMonth()); //找到下个月的第一天。
System.out.println("firstDayOfNextMonth: " + dt); //2022-07-01T13:14:15
dt = dt.with(TemporalAdjusters.lastDayOfYear()); //找到一年中的最后一天。
System.out.println("lastDayOfYear: " + dt); // 2022-12-31T13:14:15
dt = dt.with(TemporalAdjusters.firstDayOfYear()); //一年的第一天
System.out.println("firstDayOfYear: " + dt); //2022-01-01T13:14:15
dt = dt.with(TemporalAdjusters.lastInMonth(DayOfWeek.SUNDAY)); //该月的最后一个星期日
System.out.println("lastInMonth DayOfWeek.SUNDAY: " + dt); //2022-01-30T13:14:15
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# TemporalAdjuster
我们还可以自定义调节器规则,在规则里写业务逻辑等
TemporalAdjuster taj = t -> t.plus(Period.ofDays(14)); // lambda语法,增加14天
dt = dt.with(taj);
System.out.println(dt); //2022-02-13T13:14:15
1
2
3
2
3
# 实现 TemporalAdjuster
接口
我们还可以通过实现 TemporalAdjuster
接口来创建时间调整器
import java.time.LocalDate;
import java.time.temporal.ChronoField;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAdjuster;
class NextChristmas implements TemporalAdjuster {
@Override
public Temporal adjustInto(Temporal temporal) {
return temporal.with(ChronoField.MONTH_OF_YEAR, 12)
.with(ChronoField.DAY_OF_MONTH, 25);
}
}
public class JavaCustomTemporalAdjusterEx2 {
public static void main(String[] args) {
var now = LocalDate.now();
System.out.println("Today: " + now);
var xmas = now.with(new NextChristmas());
System.out.println("Next XMas: " + xmas);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 参考
上次更新: 2024/10/1 16:19:31