JAVA日期加减运算
程序员文章站
2022-06-24 22:26:20
...
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();
}
上一篇: html输入两个数实现加减乘除功能
下一篇: Java日期加减运算