如何使用java8设置工作日

时间:2016-06-14 14:28:35

标签: java datetime time java-time

我有以下Joda-Time代码设置工作日:

LocalDateTime localDateTime = new LocalDateTime(2016, 1, 1, 20,39);
LocalDateTime localDateTime1 = localDateTime.withDayOfWeek(7); 

我如何对java.time做同样的事情?我看到没有setDayOfTheWeek

LocalDateTime time;
time.getDayOfWeek()

4 个答案:

答案 0 :(得分:3)

使用time.with(TemporalAdjuster),指定DayOfWeek的实例,例如

LocalDateTime time1 = time.with(DayOfWeek.FRIDAY);

答案 1 :(得分:2)

您有几种方法可以做到:

LocalDateTime localDateTime = LocalDateTime.of(2016, 1, 1, 20, 39);

LocalDateTime ldt1 = localDateTime.with(ChronoField.DAY_OF_WEEK, 7);
LocalDateTime ldt2 = localDateTime.with(DayOfWeek.of(7));
//Or, more readable, as suggested by @AndyTurner
LocalDateTime ldt3 = localDateTime.with(DayOfWeek.SUNDAY);

答案 2 :(得分:2)

它没有setDayOfTheWeek因为LocalDateTime是不可变的,所以它没有用于修改对象的setter。 (Joda Time课程也是不可改变的!)。

在Java 8中使用它:

LocalDateTime localDateTime = LocalDateTime.of(2016, 1, 1, 20,39);
LocalDateTime localDateTime1 = localDateTime.with(DayOfWeek.SUNDAY);

答案 3 :(得分:1)

java.time API没有withDayOfWeek(DayOfWeek)方法。但是它确实有一个可以使用的通用with(TemporalAccessor)方法:

LocalDateTime dt = base.with(DayOfWeek.WEDNESDAY);

然而,这留下了关于选择哪个星期三的问题(它实际上改变了星期一到星期日的星期)。更好的方法是使用TemporalAdjuster使其更明确:

import static java.time.DayOfWeek.WEDNESDAY;
import static java.time.temporal.TemporalAdjusters.next;

LocalDateTime dt = base.with(next(WEDNESDAY));

这会将日期更改为基准日期之后的下一个星期三。请参阅TemporalAdjusters以了解可用选项:

  • next(DayOfWeek)
  • nextOrSame(DayOfWeek)
  • previous(DayOfWeek)
  • previousOrSame(DayOfWeek)
  • firstInMonth(DayOfWeek)
  • lastInMonth(DayOfWeek)
  • dayOfWeekInMonth(int, DayOfWeek)