If I have a specific date of a day, how do I get the date of that day in the previous week?

后端 未结 4 1764
长发绾君心
长发绾君心 2021-02-19 18:15

SEE ANSWER FROM @Basil Bourque for most up to date answer


For example, if I have a \"Date\" variable \"date1\" with a value of (dd/mm/yyy) 03/07/2011, which is a S

4条回答
  •  借酒劲吻你
    2021-02-19 18:36

    tl;dr

    LocalDate.of( 2011 , Month.JULY , 3 )
             .minusWeeks( 1 ) 
    

    2011-06-26

    java.time

    The Question and Answers use old outmoded date-time classes. Instead use the java.time classes.

    LocalDate

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

    LocalDate localDate = LocalDate.of( 2011 , Month.JULY , 3 ); 
    

    Alternatively, pass an integer in second argument instead of the Month enum. Pass 1-12 for January-December.

    Previous week

    You can subtract a week from the date.

    LocalDate weekPrior = localDate.minusWeeks( 1 );
    

    See this code run live at IdeOne.com.

    Previous day-of-week

    If you want a specific day of the week, use a TemporalAdjuster.

    Several such handy implementations provided in the TemporalAdjusters class (note the plural 's').

    LocalDate priorTuesday = localDate.with( TemporalAdjusters.previous( DayOfWeek.TUESDAY ) ) ;
    

    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?

    • 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
      • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
      • 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.

提交回复
热议问题