Java day of the week from string

醉酒当歌 提交于 2019-12-05 10:24:27

Here is an example of how this could happen...

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    Date date = null;
    try {
        date = format.parse("2011-10-29");
    } catch (ParseException e) {
        e.printStackTrace();
    }
    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    calendar.setTime(date);
    System.out.println("Day of the week = "
            + (calendar.get(Calendar.DAY_OF_WEEK)));
    System.out.println("Saturday? "
            + (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY));

    try {
        date = format.parse("2011-10-29");
    } catch (ParseException e) {
        e.printStackTrace();
    }
    calendar = Calendar.getInstance(TimeZone.getTimeZone("PST"));
    calendar.setTime(date);
    System.out.println("Day of the week = "
            + (calendar.get(Calendar.DAY_OF_WEEK)));
    System.out.println("Saturday? "
            + (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY));

which outputs

Day of the week = 7
Saturday? true
Day of the week = 6
Saturday? false

so yes, depending on what time zone you are in it will or will not be Saturday.

Getting true with the following code:

    try {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = format.parse("2011-10-29");
        Calendar cal = GregorianCalendar.getInstance();
        cal.setTime(date);
        System.out.println(cal.get(Calendar.DAY_OF_WEEK)==Calendar.SATURDAY);
    }
    catch(Exception e) {
        e.printStackTrace();
    }

Maybe a locale setting?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!