/**
* 获取过去的天数
* @param date
* @return
*/
public static long pastDays(Date date) {
long t = new Date().getTime()-date.getTime();
return t/(24*60*60*1000);
}
/**
* 获得指定日期的前一天
*/
public static String getSpecifiedDayBefore(String specifiedDay, int number) {
Calendar c = Calendar.getInstance();
Date date = null;
try {
date = new SimpleDateFormat("yyyy-MM-dd").parse(specifiedDay);
} catch (ParseException e) {
e.printStackTrace();
}
c.setTime(date);
int day = c.get(Calendar.DATE);
c.set(Calendar.DATE, day - number);
String dayBefore = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
return dayBefore;
}
/**
* 获得指定日期的后一天
*/
public static String getSpecifiedDayAfter(String specifiedDay, int number) {
Calendar c = Calendar.getInstance();
Date date = null;
try {
date = new SimpleDateFormat("yyyy-MM-dd").parse(specifiedDay);
} catch (ParseException e) {
e.printStackTrace();
}
c.setTime(date);
int day = c.get(Calendar.DATE);
c.set(Calendar.DATE, day + number);
String dayAfter = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
return dayAfter;
}
/**
* 获得当天时间的零点
*/
public static String getTimeOf24() {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cal.getTime());
return time;
}
/**
* 格式时间
*
* @param date
* @param format
* @return
*/
public static String getFormatDate(Date date, String format) {
if (date != null) {
SimpleDateFormat f = new SimpleDateFormat(format);
return f.format(date);
} else {
return null;
}
}
// 计算两个日期之间有多少天
public static int getDaysBetween(Date startDate, Date endDate) {
Calendar d1 = Calendar.getInstance();
d1.setTime(startDate);
Calendar d2 = Calendar.getInstance();
d2.setTime(endDate);
if (d1.after(d2)) { // swap dates so that d1 is start and d2 is end
java.util.Calendar swap = d1;
d1 = d2;
d2 = swap;
}
int days = d2.get(Calendar.DAY_OF_YEAR) - d1.get(Calendar.DAY_OF_YEAR);
int y2 = d2.get(Calendar.YEAR);
if (d1.get(Calendar.YEAR) != y2) {
d1 = (Calendar) d1.clone();
do {
days += d1.getActualMaximum(Calendar.DAY_OF_YEAR);// 得到当年的实际天数
d1.add(Calendar.YEAR, 1);
} while (d1.get(Calendar.YEAR) != y2);
}
return days;
}
/** 计算两个时间戳之间的天,时,分,秒数 */
public static String getDetailsDaysBetween(Long startTime,Long endTime){
Long interval = endTime - startTime;
int ss = 1000;
int mi = ss * 60;
int hh = mi * 60;
int dd = hh * 24;
long day = interval / dd;
long hour = (interval - day * dd) / hh;
long minute = (interval - day * dd - hour * hh) / mi;
long second = (interval - day * dd - hour * hh - minute * mi) / ss;
long milliSecond = interval - day * dd - hour * hh - minute * mi - second * ss;