您的位置:首页 > 其它

使用 Calendar 需要注意到的一点地方

2007-10-30 13:20 330 查看
Calendar cal=Calendar.getInstance();
cal.set(Integer.parseInt("2007"), Integer.parseInt("11"),Integer.parseInt("08"));
System.out.println(cal.get(Calendar.DAY_OF_MONTH));
System.out.println(cal.get(Calendar.DAY_OF_WEEK));

上面的代码可能会打印出和你所期望的不一样:

这里生成一个cal1实例,这个实例的日期现在是当前日期。这是没有错的。

但下面 cal.set(Integer.parseInt("2007"), Integer.parseInt("11"),Integer.parseInt("08"));

这种写法:

我们重新设置了日期,但是当打印出星期信息的时候,你会发现,星期信息是原来的信息,并没有根据日期的变化而变化。

API上是这样说的:

Sets the values for the fields year, month, and date. Previous values of other fields are retained. If this is not desired, call
clear
first.

意思就是,如果其余的字段不需要需要保留,则首先调用clear方法。

试验过,可以

或者使用下面的方式:

Date date = format.parse( " 2007/12/08 " );
System.out.println(date.toString());
Calendar cal=Calendar.getInstance();
cal .setTime( date);
System.out.println(cal.get(Calendar.DAY_OF_MONTH));
System.out.println(cal.get(Calendar.DAY_OF_WEEK));

这样一来就完全没有问题了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: