-2

I have written code to print the day number of week, from 1 - Monday ...

I found this:

java.time.DayOfWeek num = LocalDate.of(year, month, day).getDayOfWeek();
System.out.println(num);

Example output:

> FRIDAY

So, instead of printing the number, it prints the name of the day.

How can I fix it?

import java.time.LocalDate;
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Sinkos
  • 33
  • 2
  • 3
    Welcome to Stack Overflow. Please take the [tour] to learn how Stack Overflow works and read [ask] on how to improve the quality of your question. Then [edit] your question to include your source code as a working [mcve], which can be compiled and tested by others. It is unclear what you are asking or what the problem is. – Progman Oct 05 '22 at 19:32
  • 1
    *First day of week* varies by culture. For example, in the United States, Sunday is usually considered first day of the week, not Monday as you suggest in your Question. See [`WeekFields#getFirstDayOfWeek`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/temporal/WeekFields.html#getFirstDayOfWeek()). – Basil Bourque Oct 05 '22 at 19:56
  • If this is for printing only and you want to take the first day of the week according to the default locale into account, you may use `LocalDate.of(year, month, day).format(DateTimeFormatter.ofPattern("e", Locale.getDefault(Locale.Category.DISPLAY)))`. – Ole V.V. Oct 09 '22 at 13:40
  • To answer the question in your title: It’s very sensible to have an `enum` like `DayOfWeek` for the days of the ISO week (Monday though Sunday). For most applications this makes a lot more sense than using numbers. On the other hand meaning that when for once you do need the number, you have just a little more work to do. – Ole V.V. Oct 09 '22 at 13:46

1 Answers1

4

You can use .getValue() to obtain the day number:

int dayNumberOfWeek = LocalDate.of(2022, 10, 02).getDayOfWeek().getValue();

The Java docs for DayOfWeek says:

public int getValue()
Gets the day-of-week int value.
The values are numbered following the ISO-8601 standard, from 1 (Monday) to 7 (Sunday). See WeekFields.dayOfWeek() for localized week-numbering.

ᴇʟᴇvᴀтᴇ
  • 12,285
  • 4
  • 43
  • 66
  • 1
    This answer is very well formatted and illustrates the docs by example. To encourage _do-your-own-research before asking_, a comment pointing to the docs would have sufficed: [`int num = anyLocalDate.getDayOfWeek().getValue()`](https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/time/DayOfWeek.html#getValue()) – hc_dev Oct 05 '22 at 19:40