时间处理的工具类 DateUtil

public final class DateUtil {

 

/**

* 时间转换成字符串

* @param date

*            时间

* @param format

*            格式

* @return

*/

public static String format(Date date, String format) {

return new SimpleDateFormat(format).format(date);

}

 

/**

* 字符串转换成日期

* @param dateString

*            时间的字符串格式

* @param format

*            格式

* @return

* @throws ParseException

*/

public static Date parse(String dateString, String format) throws ParseException {

return new SimpleDateFormat(format).parse(dateString);

}

 

/**

* 取得离date时间相差几天的日期

* @param date

*            被相比的日期

* @param days

*            相差的几天(正数表示向后差几天,负数表示向前差几天)

* @return

*/

public static Date getLeaveDay(Date date, int days) {

Calendar cal = Calendar.getInstance();

cal.setTime(date);

cal.add(cal.DAY_OF_YEAR, days);

return cal.getTime();

}

 

/**

* 根据日期算年龄

* @param birthDate

* @return

*/

public static int countAge(Date birthDate) {

Calendar birthday = new GregorianCalendar();

birthday.setTime(birthDate);

Calendar currtDate = new GregorianCalendar();

int age = currtDate.get(Calendar.YEAR) - birthday.get(Calendar.YEAR);

//取得周岁,即如果生日还没过,那么将年龄减1

birthday.add(Calendar.YEAR, age);

if (birthday.after(currtDate)) {

age--;

}

return age;

}

public static Date addHour(Date date,int hours) {

Calendar cal = new GregorianCalendar();

cal.setTime(date);

cal.add(Calendar.HOUR, hours);

return cal.getTime();

}

 

/**

* 取得两个日期的期间

* @param beginDate

* @param endDate

* @return 格式0Y00M000D

*/

public static String getPeriod(Date beginDate, Date endDate) {

GetDulTime getDulTime = new GetDulTime();

   String s = getDulTime.CalDulTime(beginDate,endDate); //计算日期的区间

return s; 

}

public static java.sql.Date toSqlDate(Date date){

if(date!=null){

return new java.sql.Date(date.getTime());

}

return null;

}

 

public static void main(String[] args) throws ParseException {

System.out.println(DateUtil.countAge(DateUtil.parse("19900913", "yyyyMMdd")));

System.out.println(DateUtil.addHour(new Date(),5).toLocaleString());

System.out.println(DateUtil.getPeriod(DateUtil.parse("20120229", "yyyyMMdd"), DateUtil.parse("20130229", "yyyyMMdd")));

}

 

}

你可能感兴趣的:(Date)