English 中文(简体)
Java:我每月如何获得x天(例如) 纽约总部
原标题:Java: How do I get the date of x day in a month ( e.g. Third Monday in February 2012)

我在努力解决这一问题。

I want to setup my Calendar to let s say: Third Monday in February 2012. And I didn t find any way of doing this using Java.

例如,如果我想要确定2011年圣诞节的日历,我可以很容易地这样做:

Calendar when = Calendar.getInstance();
when.set (Calendar.MONTH, Calendar.DECEMBER);
when.set (Calendar.DAY_OF_MONTH, 25)
when.set (Calendar.YEAR, 2011);

但我错失了如何安排纪念2012年纪念日,即5月最后一个星期一。 这是我的法典,但显然是错误的,因为我完全可以假定,5月份的最后星期一将是今年5月的第4周:

Calendar when = Calendar.getInstance ();
when.set (Calendar.DAY_OF_WEEK,Calendar.MONDAY);
when.set (Calendar.MONTH, Calendar.MAY);
when.set (Calendar.WEEK_OF_MONTH, 4)
when.set (Calendar.YEAR, 2012);

关于我如何从方案上找出任何建议,其中2012年5月的一周(例如上周)是上星期一? 假设我能够掌握这一信息,我就应当能够把我的守则放在工作之上。

我需要一些基本可行的其他例子。 某些情况可以为相同情况提供确切的一天。 实例:

日期:

  • 3rd Thursday of May 2015
  • 1st Monday of June 2050
  • 4th Tuesday of December 2012
  • 2nd Wednesday of July 2000

我确实需要我的项目,我确信,这个项目很简单,但我是在没有取得任何实际成果的情况下打破我的头脑,以便: 也没有发现网上的任何东西。


Added:

奥基是我上星期一一个月来这里:

when.set (GregorianCalendar.MONTH, GregorianCalendar.MAY);
when.set (GregorianCalendar.DAY_OF_WEEK, Calendar.MONDAY);
when.set (GregorianCalendar.DAY_OF_WEEK_IN_MONTH, -1);
when.set (Calendar.YEAR, 2012);

But I am not sure how would I go about doing for example seconds Monday in the same month, like this?

when.set (GregorianCalendar.DAY_OF_WEEK_IN_MONTH, 2);

Any suggestions?

最佳回答

回答是:

public static LocalDate getNDayOfMonth(int dayweek,int nthweek,int month,int year)  {
   LocalDate d = new LocalDate(year, month, 1).withDayOfWeek(dayweek);
   if(d.getMonthOfYear() != month) d = d.plusWeeks(1);
   return d.plusWeeks(nthweek-1);
}

public static LocalDate getLastWeekdayOfMonth(int dayweek,int month,int year) {
   LocalDate d = new LocalDate(year, month, 1).plusMonths(1).withDayOfWeek(dayweek);
   if(d.getMonthOfYear() != month) d = d.minusWeeks(1);
  return d;
}

public static void main(String[] args) {
   // second wednesday of oct-2011
   LocalDate d = getNDayOfMonth( DateTimeConstants.WEDNESDAY, 2, 10, 2011);
   System.out.println(d);
   // last wednesday of oct-2011
   LocalDate dlast = getLastWeekdayOfMonth( DateTimeConstants.WEDNESDAY,  10, 2011);
   System.out.println(dlast);
}

www.un.org/french/ga/president 自Java 8(2014年)以来,新日期的Amend(包装日期:>java.time >,由Jodatime(httpa href=)https://stackoverflow.com/questions/2975221/is-joda-time-deprecated-with-java-8-date-and-api-java-time)激励。

问题回答

在2013年和2014年,对所有假期都成功测试了以下守则。 我认识到,这确实回答了最初的问题,但我认为,如果有人来担任这一职务,希望如何利用日历与假日一起工作,这或许是有益的。

public static boolean isMajorHoliday(java.util.Date date) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);

    // check if New Year s Day
    if (cal.get(Calendar.MONTH) == Calendar.JANUARY
        && cal.get(Calendar.DAY_OF_MONTH) == 1) {
        return true;
    }

    // check if Christmas
    if (cal.get(Calendar.MONTH) == Calendar.DECEMBER
        && cal.get(Calendar.DAY_OF_MONTH) == 25) {
        return true;
    }

    // check if 4th of July
    if (cal.get(Calendar.MONTH) == Calendar.JULY
        && cal.get(Calendar.DAY_OF_MONTH) == 4) {
        return true;
    }

    // check Thanksgiving (4th Thursday of November)
    if (cal.get(Calendar.MONTH) == Calendar.NOVEMBER
        && cal.get(Calendar.DAY_OF_WEEK_IN_MONTH) == 4
        && cal.get(Calendar.DAY_OF_WEEK) == Calendar.THURSDAY) {
        return true;
    }

    // check Memorial Day (last Monday of May)
    if (cal.get(Calendar.MONTH) == Calendar.MAY
        && cal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY
        && cal.get(Calendar.DAY_OF_MONTH) > (31 - 7) ) {
        return true;
    }

    // check Labor Day (1st Monday of September)
    if (cal.get(Calendar.MONTH) == Calendar.SEPTEMBER
        && cal.get(Calendar.DAY_OF_WEEK_IN_MONTH) == 1
        && cal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
        return true;
    }

    // check President s Day (3rd Monday of February)
    if (cal.get(Calendar.MONTH) == Calendar.FEBRUARY
        && cal.get(Calendar.DAY_OF_WEEK_IN_MONTH) == 3
        && cal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
        return true;
    }

    // check Veterans Day (November 11)
    if (cal.get(Calendar.MONTH) == Calendar.NOVEMBER
        && cal.get(Calendar.DAY_OF_MONTH) == 11) {
        return true;
    }

    // check MLK Day (3rd Monday of January)
    if (cal.get(Calendar.MONTH) == Calendar.JANUARY
        && cal.get(Calendar.DAY_OF_WEEK_IN_MONTH) == 3
        && cal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
        return true;
    }

    return false;

}

tl;dr

LocalDate thirdMondayInFebruary2012 = 
    YearMonth.of( 2012 , Month.FEBRUARY )
             .atDay( 1 )
             .with( TemporalAdjusters.dayOfWeekInMonth( 3 , DayOfWeek.MONDAY ) );

......

LocalDate lastMondayInMay2012 = 
    YearMonth.of( 2012 , Month.MAY )
             .atDay( 1 );
             .with( TemporalAdjusters.lastInMonth( DayOfWeek.MONDAY ) );

java.time

很容易使用 j。 现在已经取代Joda-time和麻烦的老时课的时间,与最早的Java语相配。

首先,我们需要具体说明所期望的月份。 rel=“nofollow noretinger”> 班级可以这样做。 我们从那里获得了<代码>《地方<>》,这个日期没有时间,没有时间区。

YearMonth ym = YearMonth.of( 2012 , Month.FEBRUARY ); // Or pass  2  for  February .
LocalDate ld = ym.atDay( 1 );

TemporalAdjuster接口规定将日值调整为另一个日值。 rel=“nofollow noreferer”> 班次(指复数)。 http://docs.oracle.com/javase/8/docs/api/java/time/DayOf Week.html” rel=“nofollow noreferer”>

int ordinal = 3 ; // Use  3  for  third occurrence in month  such as  3rd Monday .
LocalDate thirdMondayInFebruary2012 = ld.with( TemporalAdjusters.dayOfWeekInMonth( ordinal , DayOfWeek.MONDAY ) );

<><>Tip: 类型s-safety,并确保有效的价值。


About java.time

java.time Framework is into Java 8 and subsequently. 这些班级取代麻烦的旧的legacyjava.util。 日期<<>,rel=“nofollow noretinger”>Calendar , &

Joda-time< Project,现在载于mainance Mode,建议向以下人员迁移:a href=“http://docs.ora.com/javase/10//docs/pi/java/parm/sumeral. 班级。

欲了解更多情况,见 rel=“nofollow noreferer”<>>。 并寻找许多例子和解释。 具体定义是JSR 310

您可与您的数据库直接交换java.time物体。 使用JDBC 合规JDBC 4.2 。 无需打字,不需要<代码>java.sql.*。

获取ava。 时间段

>ThreeTen-Extra 项目延长java.time 额外课程。 该项目是今后可能增加 j的一个证明。 时间。 http://www. 33ten.org/ iii/extra/apidocs/org/ 3ten/extra/Interval.html

I do not know the "easy" way but I can suggest you the following.

  1. Set calendar to the first day of the month.
  2. Retrieve its day of the week
  3. Calculate the date of the first Monday of the month.
  4. Add 14 days using calendar.add() method. You will get the third Monday.

你们所需要的是:

public class CalculateDate {

public static void main( String ... args ) {

    Calendar c = Calendar.getInstance();
    c.set( Calendar.YEAR, 2012 );
    c.set( Calendar.MONTH , Calendar.MAY);
    c.set( Calendar.DAY_OF_MONTH, 0 );
    c.add( Calendar.DAY_OF_MONTH, -1 );

    System.out.println( c.getTime() );

    int mondaysCount = 0;

    while ( mondaysCount != 4 ) {
        c.add( Calendar.DAY_OF_MONTH, 1 );
        if ( c.get( Calendar.DAY_OF_WEEK ) == Calendar.MONDAY ) {
            mondaysCount++; 
        }       
    }

    System.out.printf( "The fourth monday of may is %s", c.getTime() );     

}

}

http://www.quartz-scheduler.org/“rel=“nofollow” Quartz Tabler?

public Date date(String cronExpression) {
    return new org.quartz.CronExpression(cronExpression).
        getNextValidTimeAfter(new Date(0));
}

System.out.println(date("0 0 0 ? May Thu#3 2015"));
System.out.println(date("0 0 0 ? Jun Mon#1 2050"));
System.out.println(date("0 0 0 ? Dec Tue#4 2012"));
System.out.println(date("0 0 0 ? Jul Wed#2 2000"));

这一简便的代码版(?)结果:

Thu May 21 00:00:00 CEST 2015
Mon Jun 06 00:00:00 CEST 2050
Tue Dec 25 00:00:00 CET 2012
Wed Jul 12 00:00:00 CEST 2000

The required CronExpression 确实有一些依赖Quartz的其余部分,因此,你可以考虑将其复制到你的项目中(对许可证的监督!)

附带说明:getNextValidtimeAfter()的内部实施为400条代码。

public String nDow(int year, int month, int nweek, int nday)
{
    Calendar cdt = Calendar.getInstance();
    cdt.set(year, month -1, 1);
    return year + "-" + month + "-" + (getPosOfWeekday(cdt.get(Calendar.DAY_OF_WEEK), nday) + ((nweek - 1) *7));
}

private int getPosOfWeekday(int startday, int nday)
{
    nday = weekDayValue(nday);
    return constructCircularArray(startday).indexOf(nday) + 1;
}

private ArrayList<Integer> constructCircularArray(int weekday)
{
    ArrayList<Integer> circularArray = new ArrayList<Integer>();
    for(int i = 0; i < 7; i++)
    {
        circularArray.add(i, weekDayValue(weekday++));
    }
    return circularArray;
}

private int weekDayValue(int x)
{
    return ((x-1) % 7) + 1;
}

这是另一种选择。 确实是:你想要哪一周(n)和其他参数,并将这一周的日期退回。 由于日历上注明了上个月的日期(例如2月29日,而不是3月7日,自3月1日第一周与最后一个星期Feb合用),如果该日期在每星期超过7个或多个,则该职能将相应调整为第二周。 希望会有所帮助。

public static int getNthWeekDay (int n, int day, int month, int year) {
    Calendar calendar = Calendar.getInstance();

    calendar.set(Calendar.DAY_OF_WEEK, day);
    calendar.set(Calendar.MONTH, month);
    calendar.set(Calendar.WEEK_OF_MONTH,n);
    calendar.set(Calendar.YEAR, year);
    if (calendar.get(Calendar.DATE) > n * 7) {
        calendar.set(Calendar.DAY_OF_WEEK,day);
        calendar.set(Calendar.MONTH, month);
        calendar.set(Calendar.WEEK_OF_MONTH,day+1);

    }
    return calendar.get(Calendar.DATE);
}




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签