我在管道中收到了几十个积压请求,比如
'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就是完美的。
非常感谢任何帮助。
答案 0 :(得分:2)
在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(受欢迎的第三方图书馆):
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(我自己的第三方库):
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);
答案 1 :(得分:1)
与日期和时间相关的所有事物的规范库是Joda Time。采用并清除所有标准java类,如Date
,Calendar
等。
它会让你的生活更美好。
关于&#34;我如何使用joda-time查找当月的第三个星期四&#34;,a stackoverflow answer for that already。我建议使用提问者发布的代码然后问题&#34;它现在是本月的第三个星期四&#34;回答:
LocalDate today = new LocalDate();
if (today.equals(calcDayOfWeekOfMonth(DateTimeConstants.THURSDAY, 3, today))) {
// do special third-Thursday processing here
}