"is this date the third thursday of the month?" - Java 图书馆?

"is this date the third thursday of the month?" - Java Library?

我有几十个积压请求正在处理中,例如

'I need this functionality to run on the third Thursday of every month, and the first Wednesday of every other month...'

我已经有一个每天运行的函数,我只需要:isThirdSundayOfMonth(date) 位附加到然后结束。

我花在考虑公历和时区的细微差别上的时间越少,我的生活就越好。

有人知道可以简化此类计算的 Java 库吗?没有 xml 配置或框架或任何东西。只要一个 .Jar 和一个文档化的、可读的 API 就完美了。

如有任何帮助,我们将不胜感激。

与日期和时间相关的所有事物的规范库是 Joda Time。采用并清除所有标准 java 类,如 DateCalendar

它会让你的生活更美好。

至于"How do I use joda-time to find the third Thursday of the month",有a Whosebug answer for that already。我建议使用提问者发布的代码,然后问题 "is it now the third Thursday of the month" 由以下人员回答:

LocalDate today = new LocalDate();
if (today.equals(calcDayOfWeekOfMonth(DateTimeConstants.THURSDAY, 3, today))) {
    // do special third-Thursday processing here
}

完整概述:

在Java-8(新标准)中:

LocalDate input = LocalDate.now(); // using system timezone
int ordinal = 3;
DayOfWeek weekday = DayOfWeek.SUNDAY;

LocalDate adjusted = 
  input.with(TemporalAdjusters.dayOfWeekInMonth(ordinal, weekday));
boolean isThirdSundayInMonth = input.equals(adjusted);

在 Joda-Time(流行的第 3 方库)中:

LocalDate input = new LocalDate(); // using system timezone
int ordinal = 3;
int weekday = DateTimeConstants.SUNDAY;

LocalDate start = new LocalDate(input.getYear(), input.getMonthOfYear(), 1);
LocalDate date = start.withDayOfWeek(weekday);
LocalDate adjusted = (
  date.isBefore(start)) 
  ? date.plusWeeks(ordinal) 
  : date.plusWeeks(ordinal - 1);
boolean isThirdSundayInMonth = input.equals(adjusted);

使用java.util.GregorianCalendar(旧标准):

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
GregorianCalendar input = new GregorianCalendar();
int ordinal = 3;
int weekday = Calendar.SUNDAY;

GregorianCalendar start =
    new GregorianCalendar(input.get(Calendar.YEAR), input.get(Calendar.MONTH), 1);
int dow = start.get(Calendar.DAY_OF_WEEK); // Sun=1, Mon=2, ...
int delta = (weekday - dow);
if (delta < 0) {
    delta += 7;
}
start.add(Calendar.DAY_OF_MONTH, delta + (ordinal - 1) * 7);
String comp1 = sdf.format(input.getTime());
String comp2 = sdf.format(start.getTime());
boolean isThirdSundayInMonth = comp1.equals(comp2);

即使使用最丑陋的库,也可能有解决方案 ;-) 我使用了字符串比较来消除任何时区影响或包括毫秒在内的时间部分。仅基于年月日的字段比较也是一个好主意。

使用 Time4J(我自己的第 3 方库):

PlainDate input = 
  SystemClock.inLocalView().today(); // using system timezone
Weekday weekday = Weekday.SUNDAY;

PlainDate adjusted = 
  input.with(PlainDate.WEEKDAY_IN_MONTH.setToThird(weekday));
boolean isThirdSundayInMonth = input.equals(adjusted);