/**
* 获取两个日期之间相差的月数
* @param date1
* @param date2
* @return
*/
public static long monthsBetween(Date date1, Date date2) {
Calendar cal1 = new GregorianCalendar();
cal1.setTime(date1);
Calendar cal2 = new GregorianCalendar();
cal2.setTime(date2);
long c = (cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR)) * 12 + cal1.get(Calendar.MONTH) - cal2.get(Calendar.MONTH);
return c;
}
/**
* 获取两个日期之间相差的天数
* @param begin
* @param end
* @return
*/
public static long daysBetween(long begin,long end){
long btn = end - begin;
long day = btn/(24*60*60*1000);
return day;
}
/**
* 获取两个日期之间相差的小时数
* @param begin
* @param end
* @return
*/
public static long hoursBetween(long begin,long end){
long btn = end - begin;
long day = btn/(24*60*60*1000);
long hour = (btn/(60*60*1000)-day*24);
return hour;
}
/**
* 根据日期获得所在周的日期
* @param mdate
* @return
*/
@SuppressWarnings("deprecation")
public static List<Date> dateToWeek(Date mdate) {
int b = mdate.getDay();
Date fdate;
List<Date> list = new ArrayList<Date>();
Long fTime = mdate.getTime() - b * 24 * 3600000;
for (int a = 1; a <= 7; a++) {
fdate = new Date();
fdate.setTime(fTime + (a * 24 * 3600000));
list.add(a-1, fdate);
}
return list;
}
/**
* 取得当前系统时间,格式为yyyyMMddHHmm
*
* @return 当前系统时间,格式为yyyyMMddHHmm
*/
public static String getDate12() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmm");
return formatter.format(new Date());
}
/**
* 得到指定时间的几分钟前的时间
* @param d 指定时间
* @param minute 分钟数
* @return
*/
public static Date getMinuteBefore(Date d, int minute) {
Calendar now = Calendar.getInstance();
now.setTime(d);
now.set(Calendar.MINUTE, now.get(Calendar.MINUTE) - minute);
return now.getTime();
}
/**
* 得到指定时间的几个小时后的时间
* @param d 指定时间
* @param hour 小时
* @return
*/
public static Date getHourAfter(Date d, int hour) {
Calendar now = Calendar.getInstance();
now.setTime(d);
now.set(Calendar.HOUR, now.get(Calendar.HOUR) + hour);
return now.getTime();
}
/**
* 得到指定时间的几个小时前的时间
* @param d 指定时间
* @param hour 小时
* @return
*/
public static Date getHourBefore(Date d, int hour) {
Calendar now = Calendar.getInstance();
now.setTime(d);
now.set(Calendar.HOUR, now.get(Calendar.HOUR) - hour);
return now.getTime();
}
/**
* 得到指定时间的几天前的时间
* @param d 指定时间
* @param hour 小时
* @return
*/
public static Date getDayBefore(Date d, int day) {
Calendar now = Calendar.getInstance();
now.setTime(d);
now.set(Calendar.DAY_OF_MONTH, now.get(Calendar.DAY_OF_MONTH) - day);
return now.getTime();
}
/**
* 得到指定时间的几月前的时间
* @param d 指定时间
* @param hour 小时
* @return
*/
public static Date getMonthBefore(Date d, int month) {
Calendar now = Calendar.getInstance();
now.setTime(d);
now.set(Calendar.MONTH, now.get(Calendar.MONTH) - month);
return now.getTime();
}
/**
* 得到指定时间的几年前的时间
* @param d 指定时间
* @param hour 小时
* @return
*/
public static Date getYearBefore(Date d, int year) {
Calendar now = Calendar.getInstance();
now.setTime(d);
now.set(Calendar.YEAR, now.get(Calendar.YEAR) - year);
return now.getTime();
}
java中与时间有关的一些常用方法
最新推荐文章于 2021-03-02 12:49:54 发布