[英]How can I find the most recent month end date with Joda time?
假设一个月结束日期是一个月中的日期,即该月中的最后一个非周末和非假日日期。 如何在Joda时间找到最近一个月的结束日期? 例如,今天的答案将是5月28日星期五,因为那是五月的月末,而五月是最近一个月的结束。
DateTime.dayOfMonth.getMaximumValue()给出了该月的最后一天。 获取当天的工作日以检查是否在周末。
一般来说:
或许它是:
这不是最有效的,但是一旦你计算它就缓存它是很便宜的,因为它将在一个月内有效。 您可以轻松计算“所有”月末日期并将其存储在查找表中。 你肯定想要计算下一个时间,因为那是当前缓存值到期的时候。
这是我快速炮制的一个片段:
import org.joda.time.*;
public class LastMonthEnd {
static int count = 0;
static boolean isWeekendOrHoliday(DateTime d) {
return (count++ < 5);
}
public static void main(String[] args) {
DateTime d = new DateTime().minusMonths(1).dayOfMonth().withMaximumValue();
while (isWeekendOrHoliday(d)) {
d = d.minusDays(1);
}
System.out.println(d);
}
}
今天( 2010-06-14 12:04:57Z
),打印出"2010-05-26T12:00:42.702Z"
。 请注意, isWeekendOrHoliday
只是实际实现的存根。 我认为真正的测试将是相当复杂的(假期部分),并且可能值得一个问题。
根据您的问题和评论,您正试图解决这样的问题:
这是财务调度库Lamma( http://lamma.io )的实现。 Date.backward(Calendar)
方法用于查找最近的工作日。
如果你真的想在Joda中实现,那么你基本上需要自己实现Date.pastMonthEnd()和Date.backward(Calendar)。
public static void main(String [] args) {
// print 2014-05-30, because 2014-05-31 is holiday
System.out.println(findDate(new Date(2014, 5, 31)));
// print 2014-04-30
System.out.println(findDate(new Date(2014, 5, 30)));
// print 2014-04-30, because the most recent working day of 2014-05-25 is not the last working day of May
System.out.println(findDate(new Date(2014, 5, 25)));
}
private static HolidayRule cal = weekends(); // let's use weekend calendar for now
public static Date findDate(Date current) {
if (cal.isHoliday(current)) {
Date lastWorkingDayOfThisMonth = current.lastDayOfMonth().backward(cal);
Date mostRecentWorkingDay = current.backward(cal);
if (lastWorkingDayOfThisMonth.equals(mostRecentWorkingDay)) {
return mostRecentWorkingDay;
} else {
return lastWorkingDayOfLastMonth(current);
}
} else {
return lastWorkingDayOfLastMonth(current);
}
}
public static Date lastWorkingDayOfLastMonth(Date d) {
return d.lastDayOfPreviousMonth().backward(cal);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.