如何找到任意日期的最近工作日? [英] How to find nearest week day for an arbitrary date?
问题描述
是否有一种优雅的方法可以使用JodaTime查找给定日期的星期几?我最初以为是setCopy()
,但这将日期设置为同一周中的特定日期 .因此,如果ld
是2011-11-27
并且day
是星期一",则下面的函数将返回2011-11-21
,而不是我想要的2011-11-28
.
Is there an elegant way to find the nearest day of the week for a given date using JodaTime? I initially thought setCopy()
would be it, but this sets the day to the particular day in the same week. Thus, if ld
is 2011-11-27
and day
is "Monday" the following function returns 2011-11-21
, and not 2011-11-28
as I want.
// Note that "day" can be _any_ day of the week, not just weekdays.
LocalDate getNearestDayOfWeek(LocalDate ld, String day) {
return ld.dayOfWeek().setCopy(day);
}
各种输入所需的输出:
2011-12-04, Monday => 2011-12-05
2011-12-04, Tuesday => 2011-12-06
2011-12-04, Wednesday => 2011-12-07
2011-12-04, Thursday => 2011-12-01
2011-12-04, Friday => 2011-12-02
2011-12-04, Saturday => 2011-12-03
2011-12-04, Sunday => 2011-12-04
2011-12-05, Monday => 2011-12-05
2011-12-05, Tuesday => 2011-12-06
2011-12-05, Wednesday => 2011-12-07
2011-12-05, Thursday => 2011-12-08
2011-12-05, Friday => 2011-12-02
2011-12-05, Saturday => 2011-12-03
2011-12-05, Sunday => 2011-12-04
下面是我想出的一种变通方法,该方法可解决当前情况下的特定限制,但是我很乐意寻求帮助,以找到始终有效的完全通用的解决方案.
Below is a work-around I came up with that works for the particular constraints in my current situation, but I'd love to get help find a completely generic solution that works always.
LocalDate getNearestDayOfWeek(LocalDate ld, String day) {
LocalDate target = ld.dayOfWeek().setCopy(day);
if (ld.getDayOfWeek() > DateTimeConstants.SATURDAY) {
target = target.plusWeeks(1);
}
return target;
}
推荐答案
在Jodatime中,这种事情应该可以执行三到四行:
In Jodatime, this kind of thing should be doable with three or four lines:
/** Given a reference LocalDate and a day of week, eg DateTimeConstants.MONDAY
Returns the nearest date with that day of week */
public static LocalDate getNearestDayOfWeek(LocalDate t0,int dow) {
LocalDate t1 = t0.withDayOfWeek(dow);
LocalDate t2 = t1.isBefore(t0) ? t1.plusWeeks(1) : t1.minusWeeks(1);
return Math.abs(Days.daysBetween(t1, t0).getDays()) <
Math.abs(Days.daysBetween(t2, t0).getDays()) ? t1 : t2;
}
或更紧凑,更高效:
public static LocalDate getNearestDayOfWeek(LocalDate t0, int dow) {
LocalDate t1 = t0.withDayOfWeek(dow);
if (t1.isBefore(t0.minusDays(3))) return t1.plusWeeks(1);
else if (t1.isAfter(t0.plusDays(3))) return t1.minusWeeks(1);
else return t1;
}
如果您想将星期几作为String传递:
And if you want to pass the day-of-the-week as String:
public static LocalDate getNearestDayOfWeek(LocalDate t0, String dow) {
return getNearestDayOfWeek(t0,t0.dayOfWeek().setCopy(dow).getDayOfWeek());
}
示例:
// prints 2011-11-28
public static void main(String[] args) throws Exception {
LocalDate today = new LocalDate(2011,11,27);
int dow = DateTimeConstants.MONDAY;
System.out.println(getNearestDayOfWeek(today ,dow ));
}
这篇关于如何找到任意日期的最近工作日?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!