如何使用 Java 日历检查今天是否是星期日
我写了几行代码,但无法正常工作。为什么?某人能给我解释一下吗?
Calendar date = Calendar.getInstance();
date.set(2010, 03, 7);
if(date.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
System.out.println("OK");
I wrote few lines of code which doesn't work correctly. Why? Could sb explain me?
Calendar date = Calendar.getInstance();
date.set(2010, 03, 7);
if(date.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
System.out.println("OK");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
为了避免犯错误,您可以使用月份的日历静态值,例如:
To avoid making mistakes, you can use Calendar static values for the month, e.g. :
月份从零开始计数:
也不要养成用前导零书写数字的习惯。这告诉 Java(以及许多其他语言)您希望将数字解释为八进制(以 8 为基数)常量,而不是十进制。
Months count from zero:
Also don't get in the habit of writing numbers with leading zeros. That tells Java (and many other languages) that you want the number interpreted as an octal (base 8) constant, not decimal.
因为 2010 年4 月7 日不是星期日。 月份从零开始:0 = 一月, 1 = 二月,2 = 三月,...
(另外,请注意,您在指定月份时使用了八进制 [
03
而不是3
]。没什么大不了的直到九月,08
是一个无效的八进制数。)Because April 7th, 2010 isn't a Sunday. Months start with zero: 0 = January, 1 = February, 2 = March, ...
(Also, side note, you've used octal when specifying the month [
03
instead of3
]. No biggie until you get to September, whereupon08
is an invalid octal number.)这是欧拉 19 的吗?
如果是这样,这里有一个提示,从 1901 年到 2000 年、从第 0 个月到第 11 个月、从第 1 天到第 31 天循环,然后问:
Is this for Euler 19?
If so, here is a tip, loop from 1901 to 2000, from months 0 to 11, from days 1-31, then ask:
可能是因为月份是从 0 开始的,所以您设置了 4 月 7 日,这是星期三。
Probably because the month is 0-based, so you set April, 7th, which is a Wednesday.
月份值从 0 开始。
Calendar 类的 set 方法的 Java 文档
。另外,如果您想检查今天(程序运行的日子:))是否是星期日,则无需设置任何内容,因为
getInstance
方法默认返回一个基于当前时间的 Calendar 对象默认区域设置的时区:The month value is 0-based.
Java docs for set method of Calendar class
.Also if you want to check if today(the day the program is run :) ) is Sunday, you need not set anything, because the
getInstance
method returns a Calendar object based on the current time in the default time zone with the default locale:对我来说,这段代码工作正常,请按毫秒设置确切的日期,然后尝试如下:-
谢谢,
普拉巴特·库马尔·卡什亚普
For me this code worked properly, please set the exact date by it millisecond and try like this:-
Thanks,
Prabhat Kumar Kashyap
cal.DAY_OF_WEEK == cal.SATURDAY
|| cal.DAY_OF_WEEK == cal.SATURDAY
应该足够好了。
cal.DAY_OF_WEEK == cal.SATURDAY
|| cal.DAY_OF_WEEK == cal.SATURDAY
should be good enough.