java 时分秒加减_JAVA日期加减运算

public static Date getBeforeMonth(Date date,int months)

{

Calendar calendar = Calendar.getInstance();

calendar.setTime(date);

calendar.set(Calendar.MONTH,calendar.get(Calendar.MONTH) - months);

return calendar.getTime();

}

1.用java.util.Calender来实现,这种实现方式才是非常准确的

public static String getBeforeDate(Date date,int days)

{

SimpleDateFormat df = new SimpleDateFormat(FORMAT_DAY);

Calendar calendar = Calendar.getInstance();

calendar.setTime(date);

calendar.set(Calendar.DAY_OF_YEAR,calendar.get(Calendar.DAY_OF_YEAR) - days);

return df.format(calendar.getTime());

}

public static String getAfterDate(Date date,int days)

{

SimpleDateFormat df = new SimpleDateFormat(FORMAT_DAY);

Calendar calendar = Calendar.getInstance();

calendar.setTime(date);

calendar.set(Calendar.DAY_OF_YEAR,calendar.get(Calendar.DAY_OF_YEAR) + days);

return df.format(calendar.getTime());

}

2.用java.text.SimpleDateFormat和java.util.Date来实现

public static String getBeforeDate(Date date,int days)

{

SimpleDateFormat df = new SimpleDateFormat(FORMAT_DAY);

Date beforeDate = new Date(date.getTime() - days * 24 * 60 * 60 * 1000);

return df.format(beforeDate);

}

public static String getAfterDate(Date date,int days)

{

SimpleDateFormat df = new SimpleDateFormat(FORMAT_DAY);

Date beforeDate = new Date(date.getTime() + days * 24 * 60 * 60 * 1000);

return df.format(beforeDate);

}

3.获取月的第一天

public static Date getMonthFirstDate(Date date)

{

Calendar calendar = Calendar.getInstance();

calendar.setTime(date);

calendar.set(Calendar.DAY_OF_MONTH,1);

calendar.set(Calendar.HOUR,0);

calendar.set(Calendar.MINUTE,0);

calendar.set(Calendar.SECOND,0);

return calendar.getTime();

}

4.获取月的最后一天

public static Date getMonthLastDate(Date date)

{

Calendar calendar = Calendar.getInstance();

calendar.setTime(date);

//先设置为下个月第一天

calendar.add(Calendar.MONTH, 1);//加一个月

calendar.set(Calendar.DATE, 1); //设置为该月第一天

calendar.add(Calendar.DATE, -1);//再减一天即为上个月最后一天

//设置时分秒

calendar.set(Calendar.HOUR,23);

calendar.set(Calendar.MINUTE,59);

calendar.set(Calendar.SECOND,59);

return calendar.getTime();

}

5. 月份加减

public static Date getBeforeMonth(Date date,int months)

{

Calendar calendar = Calendar.getInstance();

calendar.setTime(date);

calendar.set(Calendar.MONTH,calendar.get(Calendar.MONTH) - months);

return calendar.getTime();

}

分享到:

18e900b8666ce6f233d25ec02f95ee59.png

72dd548719f0ace4d5f9bca64e1d7715.png

2008-07-05 13:54

浏览 13343

评论

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值