Hernan Hernan - 1 month ago 11
Java Question

Why i'm i getting the wrong day of the week for a certain date?

I'm trying to get the day of the week that corresponds to a date.
I'm using Java's Calendar and SimpleDateFormat.

But i'm getting the wrong outputs. For example, for this dates:


  • 2016-10-09 (getting Sunday) (it's a Sunday)

  • 2016-10-10 (getting Friday) (it's a Monday)



The code:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class test {
public static void main(String[] args) throws ParseException {
String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
String date1 = "**2016-10-09**";
String date2 = "**2016-10-10**";
Date d1 = new SimpleDateFormat("yyyy-Mm-Dd").parse( date1 );
Date d2 = new SimpleDateFormat("yyyy-Mm-Dd").parse( date2 );
Calendar cal = Calendar.getInstance();
cal.setTime(d1);
String day1 = days[cal.get(Calendar.DAY_OF_WEEK)-1];
cal = Calendar.getInstance();
cal.setTime(d2);
String day2 = days[cal.get(Calendar.DAY_OF_WEEK)-1];
System.out.printf(date1+" "+day1+"\n"+date2+" "+day2);
}
}


The Output:


2016-10-09 Sunday

2016-10-10 Friday


Why Friday? The day after Sunday is Monday!


Answer

change the formatter string to yyyy-MM-dd and days array to start with sunday

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Main {
    public static void main(String[] args) throws ParseException {
        String[] days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
        String date1 = "2016-10-09";
        String date2 = "2016-10-10";
        Date d1 = new SimpleDateFormat("yyyy-MM-dd").parse( date1 );
        Date d2 = new SimpleDateFormat("yyyy-MM-dd").parse( date2 );
        Calendar cal = Calendar.getInstance();
        cal.setTime(d1);

        String day1 = days[cal.get(Calendar.DAY_OF_WEEK)-1];
        System.out.printf(date1+" "+day1+"\n");
        cal = Calendar.getInstance();
        cal.setTime(d2);
        String day2 = days[cal.get(Calendar.DAY_OF_WEEK)-1];
        System.out.printf(date1+" "+day1+"\n");
    }
}