Java实现Date日期加减
private static Date addDay(Date date, int days) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, days);
return calendar.getTime();
}
- Calendar.YEAR:年
- Calendar.MONTH:月
- Calendar.DATE:日
- Calendar.HOUR:小时
- Calendar.MINUTE:分钟
- Calendar.SECOND:秒
使用示例
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date(1618459828000L);
System.out.println(sdf.format(date));
date = addDay(date, 3);
System.out.println(sdf.format(date));
}
输出:
2021-04-15 12:10:28
2021-04-18 12:10:28
Java实现Date保留日期部分
private static Date getDate(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
// 时
calendar.set(Calendar.HOUR_OF_DAY, 0);
// 分
calendar.set(Calendar.MINUTE, 0);
// 秒
calendar.set(Calendar.SECOND, 0);
// 毫秒
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
使用示例
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date(1618459828000L);
System.out.println(sdf.format(date));
date = getDate(date);
System.out.println(sdf.format(date));
}
输出:
2021-04-15 12:10:28
2021-04-15 00:00:00
最后,谢谢你这么帅,还给我点赞和关注。
网友评论