我有以下Joda-Time代码设置工作日:
LocalDateTime localDateTime = new LocalDateTime(2016, 1, 1, 20,39);
LocalDateTime localDateTime1 = localDateTime.withDayOfWeek(7);
我如何对java.time
做同样的事情?我看到没有setDayOfTheWeek
:
LocalDateTime time;
time.getDayOfWeek()
答案 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)