java - 如何获得一个月中的序数工作日

标签 java date ordinal localdate

嗨,我想在 java 中制作一个程序,其中 days,weekNo 是参数..就像每月的第一个星期五或每月的第二个星期一..它返回日期

最佳答案

这是一个实用方法,使用 DateUtils来自 Apache Commons / Lang :

/**
 * Get the n-th x-day of the month in which the specified date lies.  
 * @param input the specified date
 * @param weeks 1-based offset (e.g. 1 means 1st week)
 * @param targetWeekDay (the weekday we're looking for, e.g. Calendar.MONDAY
 * @return the target date
 */
public static Date getNthXdayInMonth(final Date input,
    final int weeks,
    final int targetWeekDay){

    // strip all date fields below month
    final Date startOfMonth = DateUtils.truncate(input, Calendar.MONTH);
    final Calendar cal = Calendar.getInstance();
    cal.setTime(startOfMonth);
    final int weekDay = cal.get(Calendar.DAY_OF_WEEK);
    final int modifier = (weeks - 1) * 7 + (targetWeekDay - weekDay);
    return modifier > 0
        ? DateUtils.addDays(startOfMonth, modifier)
        : startOfMonth;
}

测试代码:

// Get this month's third thursday
System.out.println(getNthXdayInMonth(new Date(), 3, Calendar.THURSDAY));

// Get next month's second wednesday:
System.out.println(getNthXdayInMonth(DateUtils.addMonths(new Date(), 1),
    2,
    Calendar.WEDNESDAY)
);

输出:

Thu Nov 18 00:00:00 CET 2010
Wed Dec 08 00:00:00 CET 2010


这是一个 JodaTime相同代码的版本(我以前从未使用过 JodaTime,所以可能有更简单的方法来实现):

/**
 * Get the n-th x-day of the month in which the specified date lies.
 * 
 * @param input
 *            the specified date
 * @param weeks
 *            1-based offset (e.g. 1 means 1st week)
 * @param targetWeekDay
 *            (the weekday we're looking for, e.g. DateTimeConstants.MONDAY
 * @return the target date
 */
public static DateTime getNthXdayInMonthUsingJodaTime(final DateTime input,
    final int weeks,
    final int targetWeekDay){

    final DateTime startOfMonth =
        input.withDayOfMonth(1).withMillisOfDay(0);
    final int weekDay = startOfMonth.getDayOfWeek();
    final int modifier = (weeks - 1) * 7 + (targetWeekDay - weekDay);
    return modifier > 0 ? startOfMonth.plusDays(modifier) : startOfMonth;
}

测试代码:

// Get this month's third thursday
System.out.println(getNthXdayInMonthUsingJodaTime(new DateTime(),
    3,
    DateTimeConstants.THURSDAY));

// Get next month's second wednesday:
System.out.println(getNthXdayInMonthUsingJodaTime(new DateTime().plusMonths(1),
    2,
    DateTimeConstants.WEDNESDAY));

输出:

2010-11-18T00:00:00.000+01:00
2010-12-08T00:00:00.000+01:00

关于java - 如何获得一个月中的序数工作日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4131558/

相关文章:

java - Spring/Hibernate 测试 : Inserting test data after DDL creation

java - Powershell 静默安装 Java

mysql - 获取有序结果集中行的序数

mysql - 将序数日期 (YYYYDDD) 转换为标准日期(例如 UTC = YYYYMMDD )

windows - 如何使用序号调用导出函数

java - 不同级别的logback不同文件

java - 如何从函数返回 JButton 并使用它在 java 中的不同类中执行操作?

r - as.Date() 不遵守 POSIXct 时区

date - 在 Go/Golang 中获取当前月份的第一天和最后一天?

javascript - 在一年的最后一周添加 1 周时出现 Moment.js 错误