如何将一个月添加到日期并获得同一天 [英] How to add one month to a date and get the same day
问题描述
我尝试根据工作日添加一个月的日期。例如,日期是9月的星期一。添加后我想要有10月的星期一。
我试图在下一个日期添加一个月
I try to add one month to a date depending on weekdays. Fore example the date is the 3. Monday of September. After adding I want have the 3. Monday of October. I tried to add one month to following date
Mon Sep 17 17:30:00 MESZ 2012
使用此代码:
Calendar date = Calendar.getInstance();
date.setTimeInMillis(date_in_mil);
date.add(Calendar.DAY_OF_WEEK_IN_MONTH, 3);
但我得到了
Mon Oct 08 17:30:00 MESZ 2012
这是第二个星期一十月而不是第三。有没有人知道这是如何工作的?
which is the second Monday of Oct and not the third. Has anybody an idea how this workes?
编辑
这是我在下面的答案中使用的解决方案:
EDIT This is the solution I used like in the answer below:
int prevDayOfWeek = date.get(Calendar.DAY_OF_WEEK);
date.add(Calendar.MONTH, 1);
date.set(Calendar.DAY_OF_WEEK, prevDayOfWeek);
date.set(Calendar.DAY_OF_WEEK_IN_MONTH, week);
周数是一个月内的周数。前例1表示第一个,第二个表示第二个,依此类推。但是周也可以倒数,例如-1表示月的最后一周。
wereby week is the number of the week in a month. Fore example 1 means the first, 2 the second, and so on. But week can also count backwards, fore example -1 means the last week of month.
推荐答案
如果你想得到第3个星期一月,然后使用
设置
而不是添加
date.set(Calendar.DAY_OF_WEEK_IN_MONTH,3);
If you want get 3rd monday of month, then use
set
instead of add
date.set(Calendar.DAY_OF_WEEK_IN_MONTH, 3);
如果你想在当前日期加一个月,请使用
date.add(Calendar.MONTH,1);
if you want add one month to current date, use
date.add(Calendar.MONTH, 1);
编辑
final Calendar date = Calendar.getInstance();
date.set(2012, Calendar.SEPTEMBER, 17);
int prevDayOfWeekInMonth = date.get(Calendar.DAY_OF_WEEK_IN_MONTH);
int prevDayOfWeek = date.get(Calendar.DAY_OF_WEEK);
date.add(Calendar.MONTH, 1);
date.set(Calendar.DAY_OF_WEEK, prevDayOfWeek);
date.set(Calendar.DAY_OF_WEEK_IN_MONTH, prevDayOfWeekInMonth);
这篇关于如何将一个月添加到日期并获得同一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!