错误的星期几

huangapple go评论55阅读模式
英文:

Wrong DAY_OF_WEEK

问题

你好,我写了下面的代码,但不明白为什么它不起作用。例如对于今天(2020年4月4日),dayOfWeek 应该是7,但结果却是2...

Calendar calendar = Calendar.getInstance();
calendar.set(2020, 3, 4); // 请注意月份从0开始,所以这里的3表示四月
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
System.out.println(dayOfWeek); // 这会在控制台上打印出2
英文:

Hy, I wrote the code below and I don't understand why it's not working. For example for today (04.04.2020) dayOfWeek should be 7, but the result is 2….

    Calendar calendar = Calendar.getInstance();
    calendar.set(2020, 4, 4);
    int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
    System.out.println(dayOfWeek); //this print 2 on the console

答案1

得分: 2

错误出现在这行代码中:

calendar.set(2020, 4, 4);

它以0表示一月开始。因此正确的代码应该是:

calendar.set(2020, 3, 4);

完整代码:

Calendar calendar = Calendar.getInstance();
calendar.set(2020, 3, 4);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
System.out.println(dayOfWeek);

输出结果:

7
英文:

The error is in this line of code:

calendar.set(2020, 4, 4);

It starts with January with the number 0. So the correct code would be:

calendar.set(2020, 3, 4);

Full code:

Calendar calendar = Calendar.getInstance();
calendar.set(2020, 3, 4);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
System.out.println(dayOfWeek);

Outputs:

7

答案2

得分: 1

虽然 @Kaimson 的答案是正确的,但我会选择使用 Java 8 的 LocalDate 而不是 java.util.Calendar,你的代码将会是:

DayOfWeek.valueOf(LocalDate.now().getDayOfWeek()).name()

如果你不使用 Java 8,可以查看 Joda Time,它有类似的 API:

DateTime.now().dayOfWeek() // 返回表示当前星期几的数字,范围是 1 到 7
英文:

While @Kaimson's answer is correct, I would opt for using java8s LocalDate instead of java.util.Calendar, where you're code will be:

DayOfWeek.valueOf(LocalDate.now().getDayOfWeek()).name()

If you're not using java8, look into joda time, which has a similar API:

DateTime.now().dayOfWeek() // yields a number 1-7 representing the current day

huangapple
  • 本文由 发表于 2020年4月4日 22:44:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/61029802.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定