Java: How do I get the date of x day in a month ( e.g. Third Monday in February 2012)

前端 未结 8 1626
执笔经年
执笔经年 2020-12-09 10:44

I am somewhat struggling with this.

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

相关标签:
8条回答
  • 2020-12-09 11:44

    tl;dr

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

    …and…

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

    java.time

    Very easy to do using the java.time classes that now supplant both Joda-Time and the troublesome old date-time classes bundled with the earliest versions of Java.

    First we need to specify the desired month. The YearMonth class can do that. From there we get a LocalDate, a date without a time-of-day and without a time zone.

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

    The TemporalAdjuster interface provides for adjusting a date-time value into another date-time value. Implementations provided by the TemporalAdjusters class (notice the plural 's'). Specify a day of week using the handy DayOfWeek enum.

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

    Tip: Rather than pass mere integers for year and month across your code base, pass objects such as YearMonth, Year, Month, and DayOfWeek. Doing so eliminates ambiguity, makes your code more self-documenting, provides types-safety, and ensures valid values.


    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.

    You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

    Where to obtain the java.time classes?

    • Java SE 8, Java SE 9, and later
      • Built-in.
      • Part of the standard Java API with a bundled implementation.
      • Java 9 adds some minor features and fixes.
    • Java SE 6 and Java SE 7
      • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • Android
      • Later versions of Android bundle implementations of the java.time classes.
      • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

    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.

    0 讨论(0)
  • 2020-12-09 11:45
    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;
    }
    
    0 讨论(0)
提交回复
热议问题