日常项目当中经常会用到操作日期,抽出时间总结了一下,欢迎和大家多多沟通学习,如有任何改进意见和建议,我的QQ是1243672,欢迎联系哦。
/** * 日期操作类 * 开发公司:北京东达悦科技有限公司 * 开发人:宋海鹏 * 最后更新日期:2013-09-10 */ package com.imstudio.common; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DatetimeHelper { private static String datePattern = "yyyy-MM-dd"; private static String timePattern = datePattern + " HH:mm:ss"; private static String minDate = "1900-01-01"; public static String getDatePattern() { return datePattern; } public static String getTimePattern() { return timePattern; } public static final String DatetimeToString(Date date, String pattern) { SimpleDateFormat df = null; String dateString = ""; if (date != null) { df = new SimpleDateFormat(pattern); dateString = df.format(date); } return dateString; } public static final String DateToString(Date date) { return DatetimeToString(date, datePattern); } public static final String DatetimeToString(Date date) { return DatetimeToString(date, timePattern); } public static final Date StringToDatetime(String date, String pattern) { SimpleDateFormat df = null; Date dateValue = null; df = new SimpleDateFormat(pattern); try { dateValue = (Date) df.parse(date); } catch (ParseException pre) { return null; } return dateValue; } public static final Date StringToDate(String date) { return StringToDatetime(date, datePattern); } public static final Date StringToDatetime(String date) { return StringToDatetime(date, timePattern); } public static final String Now(String pattern) { Date dt = new Date(); SimpleDateFormat df = new SimpleDateFormat(pattern); return df.format(dt); } public static final String Now() { return Now(timePattern); } public static final String Today() { return Now(datePattern); } public static final String Today(String pattern) { return Now(pattern); } public static final Date MinDate() { return StringToDate(minDate); } public static final Long DateDiff(Date start, Date end) { long days = 0; days = (start.getTime() - end.getTime()) / (60 * 60 * 24 * 1000); return days; } public static final Long DateDiff(String start, String end) { return DateDiff(StringToDatetime(start), StringToDatetime(end)); } public static final Long DateDiff(String end) { return DateDiff(StringToDatetime(Today()), StringToDatetime(end)); } @SuppressWarnings("deprecation") public static final Long Age(Date today, Date birthday) { long age = 0; age = today.getYear() - birthday.getYear(); if (today.getMonth() == birthday.getMonth()) { age = (today.getDay() < birthday.getDay()) ? age - 1 : age; } else { age = (today.getMonth() > birthday.getMonth()) ? age : age - 1; } return age; } }