有什么好方法可以得到即将到来的星期三的日期吗?
有没有什么好的方法可以获取下周三的日期?即如果今天是星期二,我想得到这周星期三的日期;如果今天是星期三,我想得到下星期三的日期;如果今天是星期四,我想得到下周星期三的日期.
Is there a good way to get the date of the coming Wednesday? That is, if today is Tuesday, I want to get the date of Wednesday in this week; if today is Wednesday, I want to get the date of next Wednesday; if today is Thursday, I want to get the date of Wednesday in the following week.
谢谢.
推荐答案
基本算法如下:
- 获取当前日期
- 获取星期几
- 找出与星期三的不同之处
- 如果差值不是正数,则加 7(即坚持下一个/未来日期)
- 添加差异
这里有一个片段展示如何使用 java.util.Calendar
来做到这一点:
Here's a snippet to show how to do this with java.util.Calendar
:
import java.util.Calendar;
public class NextWednesday {
public static Calendar nextDayOfWeek(int dow) {
Calendar date = Calendar.getInstance();
int diff = dow - date.get(Calendar.DAY_OF_WEEK);
if (diff <= 0) {
diff += 7;
}
date.add(Calendar.DAY_OF_MONTH, diff);
return date;
}
public static void main(String[] args) {
System.out.printf(
"%ta, %<tb %<te, %<tY",
nextDayOfWeek(Calendar.WEDNESDAY)
);
}
}
相对于我的此时此地,上述代码段的输出是 "Wed, Aug 18, 2010"
.
Relative to my here and now, the output of the above snippet is "Wed, Aug 18, 2010"
.
java.util.Calendar代码>
java.util.Formatter
- 用于格式化字符串语法
相关文章