如何获取一个月中的第几个工作日

发布于 2024-10-01 03:15:35 字数 69 浏览 3 评论 0原文

嗨,我想用java制作一个程序,其中days,weekNo是参数..比如该月的第一个星期五或该月的第二个星期一..它返回日期

hi i want to make a program in java where days,weekNo is parameter ..Like First Friday of the month or second Monday of the month ..and it returns the date

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

万水千山粽是情ミ 2024-10-08 03:15:35

这是一个实用程序方法,使用 来自 Apache Commons / LangDateUtils

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

输出:

2010 年欧洲中部时间 11 月 18 日星期四 00:00:00
2010 年欧洲中部时间 12 月 8 日星期三 00:00:00


这是相同代码的 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

Here's a utility method that does that, using DateUtils from 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;
}

Test code:

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

Output:

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


And here's a JodaTime version of the same code (I've never used JodaTime before, so there's probably a simpler way to do it):

/**
 * 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;
}

Test Code:

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

Output:

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

两个我 2024-10-08 03:15:35
  public static Date getDate(int day, int weekNo, int month, int year) {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.DATE,1);
    cal.set(Calendar.YEAR, year);
    cal.set(Calendar.MONTH, month);
    for (int i = 0; i < 31; i++) {
        if (cal.get(Calendar.WEEK_OF_MONTH) == weekNo
                && cal.get(Calendar.DAY_OF_WEEK) == day) {
            return cal.getTime();
        }
        cal.add(Calendar.DATE,1);
    }
    return null;
  }

调用代码

System.out.println(""+getDate(Calendar.MONDAY, 2, Calendar.DECEMBER,2010));

输出

Mon Dec 06 15:09:00 IST 2010
  public static Date getDate(int day, int weekNo, int month, int year) {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.DATE,1);
    cal.set(Calendar.YEAR, year);
    cal.set(Calendar.MONTH, month);
    for (int i = 0; i < 31; i++) {
        if (cal.get(Calendar.WEEK_OF_MONTH) == weekNo
                && cal.get(Calendar.DAY_OF_WEEK) == day) {
            return cal.getTime();
        }
        cal.add(Calendar.DATE,1);
    }
    return null;
  }

Calling code

System.out.println(""+getDate(Calendar.MONDAY, 2, Calendar.DECEMBER,2010));

Output

Mon Dec 06 15:09:00 IST 2010
手心的海 2024-10-08 03:15:35

tl;dr

LocalDate firstFridayThisMonth =
    LocalDate.now( ZoneId.of( "America/Montreal" ) )
             .with( TemporalAdjusters.firstInMonth( DayOfWeek.FRIDAY ) )

使用 java.time

其他答案现已过时。麻烦的旧日期时间类(DateCalendar 等)现在是 遗留,被 java.time 类取代。

LocalDate

LocalDate 类表示仅日期值,没有时间和时区。

时区对于确定日期至关重要。对于任何特定时刻,全球各地的日期都会因地区而异。例如,在法国巴黎午夜过后几分钟,又是新的一天“昨天”在魁北克蒙特利尔

大陆/地区格式指定正确的时区名称 ,例如 America/Montreal非洲/卡萨布兰卡,或太平洋/奥克兰 。切勿使用 3-4 个字母的缩写,例如 ESTIST,因为它们不是真正的时区,不是标准化的,甚至不是唯一的( !)。

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );

TemporalAdjuster

< code>TemporalAdjuster 接口提供用于操作日期时间值。 java.time 类使用不可变对象,因此结果始终是一个全新的对象,其值基于原始对象。

TemporalAdjusters< /a> 类(注意复数名称)提供了几种方便的实现。其中包括获取当月内星期几的方法:firstInMonth()lastInMonth()dayOfWeekInMonth() 。所有这些都采用 DayOfWeek 枚举对象作为参数。

LocalDate firstFridayOfThisMonth = 
    today.with(
        TemporalAdjusters.firstInMonth( DayOfWeek.FRIDAY ) 
    )
;

…以及…

LocalDate secondMondayOfThisMonth = 
    today.with(
        TemporalAdjusters.dayOfWeekInMonth( 2 , DayOfWeek.MONDAY ) 
    )
;

…以及…

LocalDate thirdWednesdayOfNextMonth = 
    today.plusMonths( 1 )
         .with(  
             TemporalAdjusters.dayOfWeekInMonth( 3 , DayOfWeek.WEDNESDAY )  
         )
;

关于 java.time

java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧遗留日期时间类,例如java.util.Date, 日历, & ; SimpleDateFormat

Joda-Time 项目,现已在 维护模式,建议迁移到 java.time 类。

要了解更多信息,请参阅 Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范为 JSR 310

从哪里获取 java.time 类?

ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是 java.time 未来可能添加的内容的试验场。您可能会在这里找到一些有用的类,例如 间隔YearWeek<代码>YearQuarter,以及更多

tl;dr

LocalDate firstFridayThisMonth =
    LocalDate.now( ZoneId.of( "America/Montreal" ) )
             .with( TemporalAdjusters.firstInMonth( DayOfWeek.FRIDAY ) )

Using java.time

The other Answers are now outdated. The troublesome old date-time classes (Date, Calendar, etc.) are now legacy, supplanted by the java.time classes.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );

TemporalAdjuster

The TemporalAdjuster interface provides for manipulating date-time values. The java.time classes use immutable objects, so the result is always a fresh new object with values based on the original.

The TemporalAdjusters class (note plural name) provides several handy implementations. Amongst those are ones to get ordinal day-of-week within the month: firstInMonth(), lastInMonth(), and dayOfWeekInMonth(). All of these take an argument of a DayOfWeek enum object.

LocalDate firstFridayOfThisMonth = 
    today.with(
        TemporalAdjusters.firstInMonth( DayOfWeek.FRIDAY ) 
    )
;

…and…

LocalDate secondMondayOfThisMonth = 
    today.with(
        TemporalAdjusters.dayOfWeekInMonth( 2 , DayOfWeek.MONDAY ) 
    )
;

…and…

LocalDate thirdWednesdayOfNextMonth = 
    today.plusMonths( 1 )
         .with(  
             TemporalAdjusters.dayOfWeekInMonth( 3 , DayOfWeek.WEDNESDAY )  
         )
;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

笔芯 2024-10-08 03:15:35
Calendar cal = Calendar.getInstance();
int dayofweek = cal.get(Calendar.DAY_OF_WEEK);

这应该做你想要的。
编辑
通过更多的计算步骤,您可能会得到结果:)(抱歉混淆了您的标题)

Calendar cal = Calendar.getInstance();
int dayofweek = cal.get(Calendar.DAY_OF_WEEK);

this should do what you want.
edit:
with some more calculate steps, you could have result :) (sorry for confuse your title)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文