5

我有这个简单的代码:

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

10 月 29 日是星期六,为什么我会弄错?

4

2 回答 2

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

哪个输出

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

所以是的,取决于你所在的时区是否会是星期六。

于 2011-10-29T01:09:21.543 回答
0

使用以下代码实现:

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

也许是语言环境设置?

于 2011-10-29T01:07:36.367 回答