有没有一个很好的方式来获得星期三的日期? [英] Is there a good way to get the date of the coming Wednesday?
本文介绍了有没有一个很好的方式来获得星期三的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
也就是说,如果今天是星期二,我想在本周获得星期三的日期;如果今天是星期三,我想得到下个星期三的日期;如果今天是星期四,我想在下一周获得星期三的日期。
谢谢。
解决方案
基本算法如下:
- 获取当前日期
- 获取星期几
- 查找与星期三的差异
- 如果差异不正,则添加7(即坚持下一步未来/未来日期)
- 添加差异
以下是一段代码片段,这与 java.util.Calendar
:
import java.util。日历;
public class NextWednesday {
public static Calendar nextDayOfWeek(int dow){
日历日期= Calendar.getInstance();
int diff = dow - date.get(Calendar.DAY_OF_WEEK);
if(!(diff> 0)){
diff + = 7;
}
date.add(Calendar.DAY_OF_MONTH,diff);
返回日期;
}
public static void main(String [] args){
System.out.printf(
%ta,% nextDayOfWeek(Calendar.WEDNESDAY)
);
}
}
相对于我这里和现在,
API链接
-
java.util.Calendar
-
java.util.Formatter
- 对于格式化字符串语法
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.
Thanks.
解决方案
The basic algorithm is the following:
- Get the current date
- Get its day of week
- Find its difference with Wednesday
- If the difference is not positive, add 7 (i.e. insist on next coming/future date)
- Add the difference
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)
);
}
}
Relative to my here and now, the output of the above snippet is "Wed, Aug 18, 2010"
.
API links
java.util.Calendar
java.util.Formatter
- for the formatting string syntax
这篇关于有没有一个很好的方式来获得星期三的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文