简体   繁体   中英

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

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;
    }
}

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...

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()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM