String specificDate=2013+"-"+06+"-"+20;
String day="Monday";
如何找到星期一到来的specificDate
之后的下一个日期?
答案 0 :(得分:3)
您要么看Java's Calendar或JodaTime,因为您正在查看日期规则,我建议Joda。
答案 1 :(得分:1)
Calendar now = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(formatString);
now.setTime(sdf.parse(dateString));
int weekday = now.get(Calendar.DAY_OF_WEEK);
if (weekday != Calendar.MONDAY)
{
int days = (Calendar.SATURDAY - weekday + 2) % 7;
now.add(Calendar.DAY_OF_YEAR, days);
}
Date monday = now.getTime();
答案 2 :(得分:1)
您应该使用更高级别的日期库来为您执行此操作。不幸的是,java内置的Date和Calendar类远不够理想。您可以看一下这个库,它已经成为Java开发人员日期操作的事实标准,直到新的JDK设计完成为止。
答案 3 :(得分:1)
您应该使用Calendar类。
Calendar c1 = Calendar.getInstance();
c1.set(2013, Calendar.JUNE, 20);
int weekday = now.get(Calendar.DAY_OF_WEEK);
if (weekday != Calendar.MONDAY) {
// calculate how much to add
// the 2 is the difference between Saturday and Monday
int days = (Calendar.SATURDAY - weekday + 2) % 7;
now.add(Calendar.DAY_OF_YEAR, days);
}
答案 4 :(得分:1)
试试这个
Calendar c = new GregorianCalendar(2013, 5, 20);
int diff = Calendar.MONDAY - c.get(Calendar.DAY_OF_WEEK);
if (diff < 0) {
diff = 7 + diff;
}
c.add(Calendar.DATE, diff);
Date monday = c.getTime();
答案 5 :(得分:1)
使用标准API执行此操作的最简单方法是将星期几设置为星期一,然后提前一周:
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); // Sets c to this week's Monday
c.add(Calendar.DATE, 7); // Advances c to next week's Monday
请注意,如果您的文化中一周的第一天是星期日,而您的开始日期是星期日,则set
方法会将日期移至下一个星期一 - 而不是前一个星期一 - 并且您结束在给定日期之后计算第二个星期一。如果一周的第一天是星期一,一切都按预期工作。
答案 6 :(得分:1)
对于Java 8,您可以使用类似......
的内容LocalDate date = LocalDate.of(2013, Month.JUNE, 20);
LocalDate nextWed2 = date.with(TemporalAdjusters.nextOrSame(DayOfWeek.MONDAY));
...或
LocalDate date = LocalDate.of(2013, Month.JUNE, 20);
LocalDate nextWed2 = date.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
如果选择日期为MONDAY
,但您想要下一个MONDAY
更详细地展示了here
或者如果您更喜欢使用JodaTime ......
LocalDate date = new LocalDate(2013, DateTimeConstants.JUNE, 20);
LocalDate nextMonday = new LocalDate(date);
if (date.getDayOfWeek() >= DateTimeConstants.FRIDAY) {
nextMonday = date.plusWeeks(1);
}
nextMonday = nextMonday.withDayOfWeek(DateTimeConstants.FRIDAY);
哪个基于this answer