user6193873
user6193873

Reputation:

Get day of week not working with Calendar

I have a problem with Calendar I want to show the name of the day of week depending what day is. For March the next code was working well

    Calendar cc;
    cc = Calendar.getInstance();
    cc.set(year, month, day);
    String descriptionDay="";
    switch (cc.get(Calendar.DAY_OF_WEEK)){
        case 1:{
            descriptionDay= "Thursday";
            break;
        }
        case 2:{
            descriptionDay= "Friday";
            break;
        }
        case 3:{
            descriptionDay= "Saturday";
            break;
        }
        case 4:{
            descriptionDay= "Sunday";
            break;
        }
        case 5:{
            descriptionDay= "Monday";
            break;
        }
        case 6:{
            descriptionDay= "Tuesday";
            break;
        }
        case 7:{
            descriptionDay= "Wednesday";
            break;
        }
    }

On April, the name of week showing incorrectly and the calendar.DAY_OF_WEEK returns me different index number What i am doing wrong? Somebody help me? Thanks

Upvotes: 4

Views: 1390

Answers (3)

Joop Eggen
Joop Eggen

Reputation: 109613

In the old Calendar the full weekday can be gotten as:

System.out.printf("Today is %s%n",
    new SimpleDateFormat("EEEE", Locale.GERMANY)
        .format(Calendar.getInstance(Locale.GERMANY).getTime()));

Upvotes: 0

Your calendar in not working because the switch case is completely wrong... Monday is never ever the 5th day of the week for example...

you need to use the same constants in the calendar class... they are there for you...

  switch (cc.get(Calendar.DAY_OF_WEEK)){

              case Calendar.SUNDAY:
                descriptionDay= "Calendar.SUNDAY";
                break;
              .......... 
              ETC ETC
             default:
                 descriptionDay="";
        }

and always use the default case in the switch statement, that is a good practice...

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201527

You should be using the numerical constants from Calendar (and you don't need all those blocks). Something like,

switch (cc.get(Calendar.DAY_OF_WEEK)){
    case Calendar.THURSDAY:
        descriptionDay= "Thursday";
        break;
    case Calendar.FRIDAY:
        descriptionDay= "Friday";
        break;
    case Calendar.SATURDAY:
        descriptionDay= "Saturday";
        break;
    case Calendar.SUNDAY:
        descriptionDay= "Sunday";
        break;
    case Calendar.MONDAY:
        descriptionDay= "Monday";
        break;        
    case Calendar.TUESDAY:
        descriptionDay= "Tuesday";
        break;       
    case Calendar.WEDNESDAY:
        descriptionDay= "Wednesday";
        break;
    }
}

Upvotes: 3

Related Questions