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

2020-02-08 07:11发布

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.

标签: java
11条回答
你好瞎i
2楼-- · 2020-02-08 07:20
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();
}
查看更多
Rolldiameter
3楼-- · 2020-02-08 07:21

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.

查看更多
叼着烟拽天下
4楼-- · 2020-02-08 07:22

The Date class itself isn't enough (+: You've got to use the Calendar class here

Something along these lines

GregorianCalendar lCalendar = new GregorianCalendar();
lCalendar.setTime( aDate );
lCalendar.add(Calendar.MONTH, -3);

p.s. the snippet above is not tested to be compilable.

查看更多
够拽才男人
5楼-- · 2020-02-08 07:23

You can use

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

Hope this helps

查看更多
闹够了就滚
6楼-- · 2020-02-08 07:28

Ok with java.sql.Date (subclass of java.util.Date) and JDK's 8 LocalDate help you can do it in one line ;)

Date date = java.sql.Date.valueOf(LocalDate.now().minus(3, ChronoUnit.MONTHS));
查看更多
家丑人穷心不美
7楼-- · 2020-02-08 07:30

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 ;)

查看更多
登录 后发表回答