1、Calendar 判断是否是同一天 代码如下 :
思路 :将两个Date 类型的时间格式化成Calendar 类型的时间 在分别获取两个事件的年月日 进行对比
public static boolean isSameDay(Date date1, Date date2) {
Calendar calDateA = Calendar.getInstance();
calDateA.setTime(date1);
Calendar calDateB = Calendar.getInstance();
calDateB.setTime(date2);
return calDateA.get(Calendar.YEAR) == calDateB.get(Calendar.YEAR)
&& calDateA.get(Calendar.MONTH) == calDateB.get(Calendar.MONTH)
&& calDateA.get(Calendar.DAY_OF_MONTH) == calDateB
.get(Calendar.DAY_OF_MONTH);
}
2、Calendar 计算 当前时间 已知当前日期
public static String getYearAndMonthDay(int dayofMonth) {
Calendar rightNow = Calendar.getInstance();
Date today = new Date(System.currentTimeMillis());
rightNow.setTime(today);
rightNow.add(Calendar.MONTH, 1); //rightHow.add(Calendar.MONTH,1)
return (rightNow.get(Calendar.YEAR)+"年"+rightNow.get(Calendar.MONTH)) + "月" + dayofMonth + "日";
}
3、Calendar计算 一个月后的今天
public static String getNextDate(int dayofMonth) {
Calendar rightNow = Calendar.getInstance();
Date today = new Date(System.currentTimeMillis());
rightNow.setTime(today);
int day = rightNow.get(Calendar.DAY_OF_MONTH+1);
return rightNow.get(Calendar.YEAR) +"-"+(rightNow.get(Calendar.MONTH) + 2) + "-" + dayofMonth ;
}
4、两个时间相差多少
public static final int getDayFromTimeDiff(Date d1, Date d2) {
if (d1 == null || d2 == null) {
return 0;
}
long l1 = d1.getTime();
long l2 = d2.getTime();
long diff = l2 - l1;
int day = (int) (diff / (1000 * 3600 * 24));
return day;
}