Retrieve current week's Monday's date

前端 未结 8 2118
逝去的感伤
逝去的感伤 2020-12-01 10:59

We have a utility that will run any day between Monday - Friday. It will update some number of files inside a Content Management Tool. The last modified date associated with

8条回答
  •  自闭症患者
    2020-12-01 11:22

    tl;dr

    LocalDate previousMonday = 
        LocalDate.now( ZoneId.of( "America/Montreal" ) )
                 .with( TemporalAdjusters.previous( DayOfWeek.MONDAY ) );
    

    java.time

    Both the java.util.Calendar class and the Joda-Time library have been supplanted by the java.time framework built into Java 8 and later. See Oracle Tutorial. Much of the java.time functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

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

    Determining today's date requires a time zone, a ZoneId.

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

    The TemporalAdjuster interface (see Tutorial) is a powerful but simple way to manipulate date-time values. The TemporalAdjusters class (note the plural) implements some very useful adjustments. Here we use previous( DayOfWeek).

    The handy DayOfWeek enum makes it easy to specify a day-of-week.

    LocalDate previousMonday = today.with( TemporalAdjusters.previous( DayOfWeek.MONDAY ) );
    

    If today is Monday, and you want to use today rather than a week ago, call previousOrSame.


    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.

提交回复
热议问题