Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get DayOfWeek from an Instant.now()

Assuming the following code...

Instant x = Instant.now();

How do I get day of week from x?

like image 753
barrypicker Avatar asked May 29 '19 15:05

barrypicker


People also ask

What does instant NOW () return in Java?

Instant now() Method in Java This method requires no parameters and it returns the current instant from the system UTC clock.

Does Instant NOW () return UTC time?

The Instant now() method will query the system UTC clock to obtain the current instant. The Instant now(Clock clock) method will query the specified now to obtain the current time.

How do I get LocalDate from instant?

Get Instant object which you want to convert to LocalDate. Create ZoneId instance based on Location. Pass ZoneId to atZone() method to get ZoneDateTime . Call toLocalDate() on ZoneDateTime object to get LocalDate .


2 Answers

You have to convert it to ZonedDateTime

Instant.now().atZone(ZoneId.systemDefault()).getDayOfWeek()
like image 181
techtabu Avatar answered Oct 11 '22 15:10

techtabu


I have awarded points to techtabu, but I ended up using atOffset instead. Here is where I ended up...

int currentDayOfWeekValue = Instant.now().atOffset(ZoneOffset.UTC).getDayOfWeek().getValue();

I am amazed how difficult the Java8 datetime libraries are. There are so many variations of similar concepts...

  • Instant
  • LocalDate
  • LocalTime
  • LocalDateTime
  • OffsetDateTime
  • ZoneOffset
  • ZonedDateTime

Rhetorical questions:

Is Zulu and UTC the same or different?

What is the timezone associated with Instant.now() - the results suggest Zulu?

Why can't I manipulate an Instant object like a LocalDateTime - methods are similar but different?

How are ZonedDateTime and OffsetDateTime different - they seem to be addressing the same concept.

like image 39
barrypicker Avatar answered Oct 11 '22 14:10

barrypicker