public class DateUtil {
public enum DateType {
YEAR, MONTH, DAY, HH, MI, SS, YYYY_MM_DD, YYYYMMDD
}
public static java.sql.Date maxDate() {
return java.sql.Date.valueOf("9999-09-09");
}
/**
* 得到当前应用服务器的系统日期
*
* @return 系统日期
*/
public static Timestamp sysTimestamp() {
return new Timestamp(System.currentTimeMillis());
}
/**
* 得到当前应用服务器的系统日期
*
* @return 系统日期
*/
public static java.sql.Date sysDate() {
return new java.sql.Date(System.currentTimeMillis());
}
/**
* 得到当前应用服务器的系统时间
*
* @return 系统日期
*/
public static java.sql.Time sysTime() {
return new java.sql.Time(System.currentTimeMillis());
}
/**
* 得到当前应用服务器的系统日期
* 字符串类型
*
* @return 系统日期
*/
public static String sysDate4Str() {
return new java.sql.Date(System.currentTimeMillis()).toString();
}
/**
* 得到d1与d2之间相差数值
*
* 数值可以为年份,DateType.YEAR
* 数值可以为月份,DateType.MONTH
* 数值可以为天数,DateType.DAY
* 数值可以为小时,DateType.HH
* 数值可以为分钟,DateType.MI
* 数值可以为秒,DateType.SS
*
* @param d1
* 日期1(较大的日期)
* @param d2
* 日期2(较小的日期)
* @param dataType
* 数值类型
* @return 相差数值
* d1早于d2时,返回-1。
* dateType类型不正确时,返回-2。
*/
public static int dateBetween(Date d1, Date d2, DateType dateType) {
if(d1.equals(d2)){
return 0;
}
if (!d2.before(d1)) {
return -1;
}
Calendar c1 = Calendar.getInstance();
c1.setTime(d1);
Calendar c2 = Calendar.getInstance();
c2.setTime(d2);
if (DateType.YEAR.equals(dateType)) {
return c1.get(Calendar.YEAR) - c2.get(Calendar.YEAR);
}
if (DateType.MONTH.equals(dateType)) {
return (c1.get(Calendar.YEAR)
- c2.get(Calendar.YEAR)) * 12 + c1.get(Calendar.MONTH) - c2.get(Calendar.MONTH);
}
if (DateType.DAY.equals(dateType)) {
return (int) ((c1.getTimeInMillis() - c2.getTimeInMillis()) / 86400000L);
}
if (DateType.HH.equals(dateType)) {
return (int) ((c1.getTimeInMillis() - c2.getTimeInMillis()) / 3600000L);
}
if (DateType.MI.equals(dateType)) {
return (int) ((c1.getTimeInMillis() - c2.getTimeInMillis()) / 60000L);
}
if (DateType.SS.equals(dateType)) {
return (int) ((c1.getTimeInMillis() - c2.getTimeInMillis()) / 1000L);
}
return -2;
}
}