簡體   English   中英

“這個日期是每月的第三個星期四嗎?”-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就是完美的。

任何幫助將非常感激。

完整概述:

在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(受歡迎的3rd-party-library)中:

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(我自己的3rd-party-library):

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);

有關日期和時間的所有事物的規范庫是Joda Time 采納並清除所有標准Java類,例如DateCalendar等。

它將使您的生活更加美好。

至於“我如何使用joda-time查找該月的第三個星期四”,已經有一個stackoverflow答案 我建議使用提問者發布的代碼,然后通過以下方式回答問題:“現在是每月的第三個星期四嗎?”

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM