How to reduce one month from current date and stored in date variable using java?

前端 未结 7 1838
天命终不由人
天命终不由人 2020-12-24 04:32

How to reduce one month from current date and want to sore in java.util.Date variable im using this code but it\'s shows error in 2nd line

 java         


        
相关标签:
7条回答
  • 2020-12-24 05:12

    Using new java.time package in Java8 and Java9

    import java.time.LocalDate;
    
    LocalDate mydate = LocalDate.now(); // Or whatever you want
    mydate = mydate.minusMonths(1);
    

    The advantage to using this method is that you avoid all the issues about varying month lengths and have more flexibility in adjusting dates and ranges. The Local part also is Timezone smart so it's easy to convert between them.

    As an aside, using java.time you can also get the day of the week, day of the month, all days up to the last of the month, all days up to a certain day of the week, etc.

    mydate.plusMonths(1);
    mydate.with(TemporalAdjusters.next(DayOfWeek.SUNDAY)).getDayOfMonth();
    mydate.with(TemporalAdjusters.lastDayOfMonth());
    
    0 讨论(0)
  • 2020-12-24 05:17

    Using JodaTime :

    Date date = new DateTime().minusMonths(1).toDate();
    

    JodaTime provides a convenient API for date manipulation.

    Note that similar Date API will be introduced in JDK8 with the JSR310.

    0 讨论(0)
  • 2020-12-24 05:18

    Use Calendar:

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.MONTH, -1);
    Date result = cal.getTime();
    
    0 讨论(0)
  • 2020-12-24 05:22

    Starting from Java 8, the suggested way is to use the Date-Time API rather than Calendar.

    If you want a Date object to be returned:

    Date date = Date.from(ZonedDateTime.now().minusMonths(1).toInstant());
    

    If you don't need exactly a Date object, you can use the classes directly, provided by the package, even to get dates in other time-zones:

    ZonedDateTime dateInUTC = ZonedDateTime.now(ZoneId.of("Pacific/Auckland")).minusMonths(1);
    
    0 讨论(0)
  • 2020-12-24 05:22

    you can use Calendar

        java.util.Date da = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(da);
        cal.add(Calendar.MONTH, -1);
        da = cal.getTime();
    
    0 讨论(0)
  • 2020-12-24 05:23
    Calendar calNow = Calendar.getInstance()
    
    // adding -1 month
    calNow.add(Calendar.MONTH, -1);
    
    // fetching updated time
    Date dateBeforeAMonth = calNow.getTime();
    
    0 讨论(0)
提交回复
热议问题