java.util.Date - Deleting three months from a date?

前端 未结 11 1572
北荒
北荒 2020-12-14 05:30

I have a date of type java.util.Date

I want to subtract three months from it.

Not finding a lot of joy in the API.

相关标签:
11条回答
  • 2020-12-14 06:12

    You can use Apache Commons Lang3 DateUtils addMonths function.

    static Date addMonths(Date date, int amount)
    

    Adds a number of months to a date returning a new object. The original Date is unchanged. The amount to add, may be negative, so you can go 3 months back.

    0 讨论(0)
  • 2020-12-14 06:12

    String startDate="15/10/1987";

        Date date = new SimpleDateFormat("dd/MM/yyyy").parse(startDate);
        String formattedDate = new SimpleDateFormat("yyyy-MM-dd").format(date);
        LocalDate today = LocalDate.parse(formattedDate);
        String endDate=today.minusMonths(3).toString();
    
    0 讨论(0)
  • 2020-12-14 06:13
    public static Date getDateMonthsAgo(int numOfMonthsAgo)
    {
        Calendar c = Calendar.getInstance(); 
        c.setTime(new Date()); 
        c.add(Calendar.MONTH, -1 * numOfMonthsAgo);
        return c.getTime();
    }
    

    will return the date X months in the past. Similarily, here's a function that returns the date X days in the past.

    public static Date getDateDaysAgo(int numOfDaysAgo)
    {
        Calendar c = Calendar.getInstance(); 
        c.setTime(new Date()); 
        c.add(Calendar.DAY_OF_YEAR, -1 * numOfDaysAgo);
        return c.getTime();
    }
    
    0 讨论(0)
  • 2020-12-14 06:14

    You want today - 3 Month formatted as dd MMMM yyyy

         SimpleDateFormat format = new SimpleDateFormat("dd MMMM yyyy");
    
         Calendar c = Calendar.getInstance(); 
         c.setTime(new Date()); 
         c.add(Calendar.MONTH, -3);
    
         Date d = c.getTime();
         String res = format.format(d);
    
         System.out.println(res);
    

    So this code can do the job ;)

    0 讨论(0)
  • 2020-12-14 06:16

    I always recommend Joda for this sort of stuff. It has a much nicer API, and doesn't suffer from threading issues that the standard Java date/time has (e.g. issues with SimpleDateFormat, or general mutability).

    e.g.

    DateTime result = dt.minusMonths(3);
    
    0 讨论(0)
  • 2020-12-14 06:18

    You can use

    Date d1 = new Date()
    d1.setMonth(d1.month-3)
    

    Hope this helps

    0 讨论(0)
提交回复
热议问题