Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set a weekday using java8

I have the following Joda-Time code which sets the weekday:

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

How can I do the same with java.time? I see that there is no setDayOfTheWeek:

LocalDateTime time;
time.getDayOfWeek()
like image 441
Elad Benda2 Avatar asked Dec 18 '22 16:12

Elad Benda2


2 Answers

Use time.with(TemporalAdjuster), specifying an instance of DayOfWeek, e.g.

LocalDateTime time1 = time.with(DayOfWeek.FRIDAY);
like image 103
Andy Turner Avatar answered Jan 05 '23 10:01

Andy Turner


It has no setDayOfTheWeek because LocalDateTime is immutable, so it has no setters to modify the object. (Joda Time classes are also immutable!).

Use this in Java 8:

LocalDateTime localDateTime = LocalDateTime.of(2016, 1, 1, 20,39);
LocalDateTime localDateTime1 = localDateTime.with(DayOfWeek.SUNDAY);
like image 24
Jesper Avatar answered Jan 05 '23 08:01

Jesper