javaandroidcalendardayofweek

mistake getting day of week


I want to get the day of the week (Monday, Tuesday, ..) from this function that receives as parameters 3 int that are the year the month and day, I have tried both Calendar and GregorianCalendar and it still gives me error, for example if I pass the date today (2017,11,04) it gives me result of the day of the week number 5, Thursday being today Tuesday I leave you the code

String diaSemana (int dia, int mes, int ano)
{
    String letraD="";
    /*Calendar c = Calendar.getInstance();
    c.set(ano, mes, dia, 0, 0, 0);
    nD=c.get(Calendar.DAY_OF_WEEK);*/
    TimeZone timezone = TimeZone.getDefault();
    Calendar calendar = new GregorianCalendar(timezone);
    calendar.set(ano, mes, dia);
    int nD=calendar.get(Calendar.DAY_OF_WEEK);
    Log.i("result","diaSemana: "+nD+" dia:"+dia+" mes:"+mes+ "año:" +ano);
    switch (nD){
            case 0: letraD = "D";
                break;
            case 1: letraD = "L";
                break;
            case 2: letraD = "M";
                break;
            case 3: letraD = "X";
                break;
            case 4: letraD = "J";
                break;
            case 5: letraD = "V";
                break;
            case 6: letraD = "S";
                break;
        }

        return letraD;
}

Log.i shows this message:

diaSemana:5 dia:11 mes:4 año:2017


Solution

  • The problem is that months start with 0: January = 0, February = 1 etc. Use this:

    calendar.set(ano, mes - 1, dia);