Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java days of week calculation

Tags:

java

enums

days

I have an Enum for Days of week (with Everyday, weekend and weekdays) as follows where each entry has an int value.

public enum DaysOfWeek {


  Everyday(127),
  Weekend(65),
  Weekdays(62), 
  Monday(2),
  Tuesday(4),
  Wednesday(8),
  Thursday(16),
  Friday(32), 
  Saturday(64),
  Sunday(1);

  private int bitValue;

  private DaysOfWeek(int n){
    this.bitValue = n;
  }

  public int getBitValue(){
    return this.bitValue;
  }
}

Given a TOTAL of any combination of the values, what would be the simplest way to calculate all individual values and make an arraylist from it. For example given the number 56 (i.e. Wed+Thur+Fri), how to calculate the days.

like image 434
Shahid Avatar asked Mar 07 '26 23:03

Shahid


1 Answers

The correct way to represent a collection of enum values is to use an EnumSet. This uses a bit vector internally. But exposing such an implementation detail as in your code is not a good idea. We're doing OO here, not bit-twiddling.

Additionally, you are mixing the concepts of a single value and a collection of values, which will likely lead to headaches down the road.

Example using the DayOfWeek enum built into Java 8 and later.

EnumSet<DayOfWeek> weekend = EnumSet.of( DayOfWeek.SATURDAY , DayOfWeek.SUNDAY );

Boolean isTodayWeekend = weekend.contains( LocalDate.now().getDayOfWeek() );
like image 177
Michael Borgwardt Avatar answered Mar 09 '26 11:03

Michael Borgwardt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!