gpt4 book ai didi

java - 设置日历实例的时间

转载 作者:搜寻专家 更新时间:2023-11-01 01:26:45 24 4
gpt4 key购买 nike

我正在尝试为 Calendar 实例设置时间,但我遇到了奇怪的行为。让我们看一些例子:

Calendar c = Calendar.getInstance();
//c.setTime(date);

c.set(date.getYear(), (date.getMonth() - 1), date.getDay());
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);

当我使用 setTime() 设置时间时,它设置了错误的日期。第二个(已弃用)set(year, month, day) 工作正常。我以前从未遇到过这个 - 我认为它在两种情况下都使用默认时区,所以它应该是相同的。有人可以给我解释一下吗?

==================== 编辑:让我们用另一种方式问:

Date date = new Date();
Calendar c1 = Calendar.getInstance();
c1.setTime(date);

Calendar c2 = Calendar.getInstance();
c2.set(date.getYear(), (date.getMonth() - 1), date.getDay());

int day1 = c1.get(Calendar.DAY_OF_WEEK);
int day2 = c2.get(Calendar.DAY_OF_WEEK);

// day1 != day2 ---> I'd like to know - WHY?

所以现在日期如下:

date: Nov 5, 2013 4:27:02 PM
day1: 3
day2: 1
time: 1383665222638
timezone: Europe/Prague

最佳答案

这一行并不像你想象的那样:

c2.set(date.getYear(), (date.getMonth() - 1), date.getDay());

Date 类中弃用的方法是这样工作的:

  • getYear() 返回年份 - 1900,因此例如 1986 返回为 86,2013 返回为 113。
  • getMonth() 返回月份 - 1,因此返回的 11 月为 10。减去 1 得到 10 月。
  • getDay() 返回星期几;星期二返回为 2。

因此,根据您的日期,您将日历的日期设置为 113 年 10 月 2 日。API 的正确用法是:

c2.set(1900+date.getYear(), date.getMonth(), date.getDate());

关于java - 设置日历实例的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19792066/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com