java.time.DayOfWeek
Java 8 and later has such an enum built-in, java.time.DayOfWeek
.
Per the ISO 8601 standard, the week is defined as Monday-Sunday, numbered 1-7.
int dayNumber = DayOfWeek.MONDAY.getValue() ; // 1 = Monday, 7 = Sunday.
Convert from ISO 8601 style to US style
If you want a week as commonly used in the United States, with Sunday being first, use math. Calculate modulo 7 then plus 1.
( DayOfWeek.SUNDAY.getValue() % 7 ) + 1
Like this:
System.out.println( ( DayOfWeek.SUNDAY.getValue() % 7 ) + 1 ) ;
System.out.println( ( DayOfWeek.MONDAY.getValue() % 7 ) + 1 ) ;
System.out.println( ( DayOfWeek.TUESDAY.getValue() % 7 ) + 1 ) ;
System.out.println( ( DayOfWeek.WEDNESDAY.getValue() % 7 ) + 1 ) ;
System.out.println( ( DayOfWeek.THURSDAY.getValue() % 7 ) + 1 ) ;
System.out.println( ( DayOfWeek.FRIDAY.getValue() % 7 ) + 1 ) ;
System.out.println( ( DayOfWeek.SATURDAY.getValue() % 7 ) + 1 ) ;
1
2
3
4
5
6
7
You question is contradictory and unclear, so I am not sure of your goal if you Sunday-Saturday being 0-6, then use above math but do not add one.
( DayOfWeek.SUNDAY.getValue() % 7 ) // Sunday = 0, Monday = 1 , … , Saturday = 6.
java.util.Calendar
constants
While I would never recommend using the legacy Date
/Calendar
classes, but for your information, the java.util.Calendar
class defines a series of int
constants (not an enum) for days of the week where Calendar.SUNDAY
is 1
and so on to Calendar.SATURDAY
is 7
.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.