来自字符串的Java星期几

out*_*d3r 5 java calendar date dayofweek simpledateformat

我有这个简单的代码:

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = format.parse("2011-10-29");
calendar.setTime(date);
Log.d("Debug","Day of the week = "+(calendar.get(Calendar.DAY_OF_WEEK)==Calendar.SATURDAY));
Run Code Online (Sandbox Code Playgroud)

十月二十九日是星期六,为什么我会弄错?

Cra*_*igy 5

这是一个如何发生这种情况的例子......

    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));
Run Code Online (Sandbox Code Playgroud)

哪个输出

Day of the week = 7
Saturday? true
Day of the week = 6
Saturday? false
Run Code Online (Sandbox Code Playgroud)

所以,是的,根据你所在的时区,它将会是或不会是星期六.