Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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


1 Answers

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;
    }
}
like image 53
Elliott Frisch Avatar answered Oct 28 '25 13:10

Elliott Frisch