DateUtil DateUtil日期工具类
开发者博客:www.developsearch.com
[code="java"]/**
* 日期工具类
*
* @author chenxin
* @version [版本号, 2012-5-21]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class DateUtil {
/**
* 默认的格式:yyyy-MM-dd
*/
public static final String PATTERN_DEFAULT = "yyyy-MM-dd";
public static final String FORMAT_STANDARD = "yyyy-MM-dd HH:mm:ss";
public static final String FORMAT_YYYYMMDD = "yyyyMMdd";
public static final String FORMAT_YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
public static final String CHINESE_SHORT_DATE = "yyyy年M月d日";
private static final String[] weekDays = { "", "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
/**
* 转换日期格式
* @param dateStr 日期字符串
* @param src 日期源格式
* @param dest 日期转后后的目标格式
* @return
* 转换格式后的日期字符串
* @throws ParseException 如果格式转换失败,则抛出异常
*/
public static String changeDateStrFormate(String dateStr, String src,
String dest) throws ParseException
{
SimpleDateFormat sdf = new SimpleDateFormat(src);
Date date = sdf.parse(dateStr);
sdf = new SimpleDateFormat(dest);
return sdf.format(date);
}
/**
* 将字符串转换为Date类型
* @param dateStr 日期字符串
* @param pattern 格式
* @return Date对象
* @throws ParseException 当进行格式化的时候失败,抛出该异常。
*/
public static Date getDateByString(String dateStr, String pattern) throws ParseException{
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.parse(dateStr);
}
/**
* 将Date类型转换为String类型
* @param date 日期
* @param pattern 格式
* @return 日期对应格式的字符串
* @throws ParseException
* 当格式转换出现异常,抛出
*/
public static String getStringByDate(Date date, String pattern) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format(date);
}
/**
* 判断两个日期是否为同年同月
*
* @param date1 date1
* @param date2 date2
* @return boolean
* @see [类、类#方法、类#成员]
*/
public static boolean isSameYYYYMM(Date date1, Date date2)
{
Calendar c1 = Calendar.getInstance();
c1.setTime(date1);
Calendar c2 = Calendar.getInstance();
c2.setTime(date2);
return (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR)) && (c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH));
}
/**
* 返回当前是本年度的第几周
*
* @param date
* @return int [返回类型说明]
*/
public static int getWeekNumOfYear(Date date)
{
Calendar c = Calendar.getInstance();
c.setTime(date);
c.setFirstDayOfWeek(Calendar.MONDAY);
return c.get(Calendar.WEEK_OF_YEAR);
}
/**
* date转timestamp类型
*/
public static Timestamp convertDate2TStamp(Date date)
{
if (null == date)
{
return null;
}
return new Timestamp(date.getTime());
}
/**
* 以分钟为单位对时间进行调整
*
* @param time 要调整的时间
* @param minite 增加的分钟数
*
* @return String 调整后的时间
*/
public static String addMinute(String time, int minite)
{
if (StringUtils.isEmpty(time))
{
return "";
}
Calendar calendar = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat(FORMAT_STANDARD);
Date date = null;
try
{
date = dateFormat.parse(time);
}
catch (ParseException e)
{
return "";
}
calendar.setTimeInMillis(date.getTime());
calendar.add(Calendar.MINUTE, minite);
return dateFormat.format(calendar.getTime());
}
/**
* 以分钟为单位对时间进行调整
*
* @param time 要调整的时间
* @param minite 增加的分钟数
*
* @return String 调整后的时间
*/
public static Date addMinute(Date requestTime, int minite)
{
if (null == requestTime)
{
return null;
}
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(requestTime.getTime());
calendar.add(Calendar.MINUTE, minite);
return calendar.getTime();
}
/**
* 获取几天前的日期
*
* @param days
* @return [参数说明]
*
* @return Date [返回类型说明]
* @exception throws [违例类型] [违例说明]
* @see [类、类#方法、类#成员]
*/
public static Date getBeforeDateInDay(int days)
{
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -days);
return calendar.getTime();
}
/**
* yyyy-MM-ddTHH:mm:ss.SSSzzzzz格式字符串转换成日期类型
*
* @param s 要转换的字符串
* @param errorMessage 转换失败时的信息
* @return 转换后的日期
*/
public static Date xmlDateTimeStr2XMLDateTime(String s, String errorMessage)
{
if ((s == null) || "".equals(s.trim()))
{
return null;
}
else
{
try
{
XMLGregorianCalendar calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(s);
return calendar.toGregorianCalendar().getTime();
}
catch (Exception e)
{
return null;
}
}
}
/**
* 日期类型转换成yyyy-MM-ddTHH:mm:ss.SSSzzzzz格式字符串
*
* @param date Date日期
* @param errorMessage 转换失败时的信息
* @return String型字符串
*/
public static String xmlDateTime2xmlDateTimeStr(Date date, String errorMessage)
{
if (date == null)
{
return errorMessage;
}
else
{
Calendar ca = Calendar.getInstance();
ca.setTime(date);
XMLGregorianCalendar calendar = null;
try
{
calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar((GregorianCalendar)ca);
}
catch (Exception e)
{
return errorMessage;
}
return calendar.toString();
}
}
/**
* 得到当前格林威治的日期和时间
*
* @return String
*/
public static String getUTCDateTime()
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
TimeZone tz = TimeZone.getTimeZone("Etc/UTC");
sdf.setTimeZone(tz);
Calendar calendar = Calendar.getInstance();
return sdf.format(calendar.getTime());
}
/**
*
* @param date
* @param date2
* @return date2-date的天数
*/
public static long getDaysInterval(Date date, Date date2) {
return (date2.getTime() - date.getTime()) / 86400000;
}
public static java.sql.Timestamp getTimestamp(){
return java.sql.Timestamp.valueOf(getNowDateTime());
}
/**
* @param days
* @return 和当前相差days天的日期
*/
public static String getDate(int days) {
Date date = new Date();
date.setTime(date.getTime() + 86400000L * days);
return date2string(date);
}
/**
*
* @param date
* @return date对应的年
*/
public static int getYear(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.YEAR);
}
public static int getNowYear() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
return calendar.get(Calendar.YEAR);
}
/**
*
* @param date
* @return date对应的月
*/
public static int getMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.MONTH) + 1;
}
public static int getNowMonth() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
return calendar.get(Calendar.MONTH) + 1;
}
/**
*
* @param date
* @return 对应的天
*/
public static int getDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.DAY_OF_MONTH);
}
public static int getNowDay() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
return calendar.get(Calendar.DAY_OF_MONTH);
}
/**
* 根据日期算年龄
* @param Date 出生日期
*/
public static int yearOLD(Date birthDay)
{
Calendar sysCalendar=Calendar.getInstance();
Calendar birCalendar=Calendar.getInstance();
birCalendar.setTime(birthDay);
if(sysCalendar.get(Calendar.MONTH)>birCalendar.get(Calendar.MONTH))
return sysCalendar.get(Calendar.YEAR)-birCalendar.get(Calendar.YEAR)+1;
else
return sysCalendar.get(Calendar.YEAR)-birCalendar.get(Calendar.YEAR);
}
/**
* 格式化今日中文短日期
*
* @return
*/
public static final String formatChineseShortToday() {
SimpleDateFormat sdf = new SimpleDateFormat(CHINESE_SHORT_DATE);
return sdf.format(new Date());
}
/**
* 得到中文星期
*
* @return
*/
public static final String getChineseWeekDay(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
return weekDays[c.get(Calendar.DAY_OF_WEEK)];
}
/**
* 日期天数增加
*
* @param date
* @param days
* @return
*/
public static Date addDays(Date date, int days) {
if (checkPara(date)) {
return null;
}
if (0 == days) {
return date;
}
Locale loc = Locale.getDefault();
Calendar cal = new GregorianCalendar(loc);
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, days);
return cal.getTime();
}
/**
* 日期天数减少
*
* @param date
* @param days
* @return
*/
public static Date minusDays(Date date, int days) {
return addDays(date, (0 - days));
}
/**
* 按时间格式相加
*
* @param dateStr
* 原来的时间
* @param pattern
* 时间格式
* @param type
* "year"年、"month"月、"day"日、"week"周、 "hour"时、"minute"分、"second"秒
* 通过常量来设置,e.g.DateFormatUtil.YEAR
* @param count
* 相加数量
* @return
*/
public static String addDate(String dateStr, String pattern, String type,
int count) {
if (checkPara(dateStr) || checkPara(pattern) || checkPara(type)) {
return "";
}
if (0 == count) {
return dateStr;
}
Date date = parseStrToCustomPatternDate(dateStr, pattern);
Locale loc = Locale.getDefault();
Calendar cal = new GregorianCalendar(loc);
cal.setTime(date);
if (DateFormatUtil.YEAR.equals(type)) {
cal.add(Calendar.YEAR, count);
} else if (DateFormatUtil.MONTH.equals(type)) {
cal.add(Calendar.MONTH, count);
} else if (DateFormatUtil.DAY.equals(type)) {
cal.add(Calendar.DAY_OF_MONTH, count);
} else if (DateFormatUtil.WEEK.equals(type)) {
cal.add(Calendar.WEEK_OF_MONTH, count);
} else if (DateFormatUtil.HOUR.equals(type)) {
cal.add(Calendar.HOUR, count);
} else if (DateFormatUtil.MINUTE.equals(type)) {
cal.add(Calendar.MINUTE, count);
} else if (DateFormatUtil.SECOND.equals(type)) {
cal.add(Calendar.SECOND, count);
} else {
return "";
}
return formatDate(cal.getTime(), pattern);
}
/**
* 那时间格式相减
*
* @param dateStr
* @param pattern
* @param type
* @param count
* @return
*/
public static String minusDate(String dateStr, String pattern, String type,
int count) {
return addDate(dateStr, pattern, type, (0 - count));
}
/**
* 日期大小比较
*
* @param dateStr1
* @param dateStr2
* @param pattern
* @return
*/
public static int compareDate(String dateStr1, String dateStr2,
String pattern) {
if (checkPara(dateStr1) || checkPara(dateStr2) || checkPara(pattern)) {
return 888;
}
Date date1 = DateFormatUtil.parseStrToCustomPatternDate(dateStr1,
pattern);
Date date2 = DateFormatUtil.parseStrToCustomPatternDate(dateStr2,
pattern);
return date1.compareTo(date2);
}
/**
* 获得这个月的第一天
*
* @param dateStr
* @return
*/
public static String getFirstDayInMonth(String dateStr) {
if (checkPara(dateStr)) {
return "";
}
Calendar cal = DateFormatUtil.parseStrToCalendar(dateStr);
int firstDay = cal.getActualMinimum(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_MONTH, firstDay);
return DateFormatUtil.formatDate(cal.getTime(),
DateFormatUtil.DATE_FORMAT);
}
/**
* 判断是不是当月的第一天
* @param dateStr
* @return
*/
public static boolean isFirstDayInMonth(String dateStr){
if (checkPara(dateStr)) {
return false;
}
Calendar cal = DateFormatUtil.parseStrToCalendar(dateStr);
int firstDay = cal.getActualMinimum(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_MONTH, firstDay);
String day = DateFormatUtil.formatDate(cal.getTime(),
DateFormatUtil.DATE_FORMAT);
if (dateStr.equals(day)) {
return true;
}
return false;
}
/**
* 判断是不是当月的最后一天
* @param dateStr
* @return
*/
public static boolean islastDayInMonth(String dateStr){
if (checkPara(dateStr)) {
return false;
}
Calendar cal = DateFormatUtil.parseStrToCalendar(dateStr);
int firstDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_MONTH, firstDay);
String day = DateFormatUtil.formatDate(cal.getTime(), DateFormatUtil.DATE_FORMAT);
if (dateStr.equals(day)) {
return true;
}
return false;
}
/**
* 获得这个月的最后一天
*
* @param dateStr
* @return
*/
public static String getLastDayInMonth(String dateStr) {
if (checkPara(dateStr)) {
return "";
}
Calendar cal = DateFormatUtil.parseStrToCalendar(dateStr);
int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_MONTH, lastDay);
return DateFormatUtil.formatDate(cal.getTime(),
DateFormatUtil.DATE_FORMAT);
}
/**
* 获得这周的第一天
*
* @param dateStr
* @return
*/
public static String getFirstDayInWeek(String dateStr) {
if (checkPara(dateStr)) {
return "";
}
Calendar cal = DateFormatUtil.parseStrToCalendar(dateStr);
int firstDay = cal.getActualMinimum(Calendar.DAY_OF_WEEK);
cal.set(Calendar.DAY_OF_WEEK, firstDay);
return DateFormatUtil.formatDate(cal.getTime(),
DateFormatUtil.DATE_FORMAT);
}
/**
* 获得这周的最后一天
*
* @param dateStr
* @return
*/
public static String getLastDayInWeek(String dateStr) {
if (checkPara(dateStr)) {
return "";
}
Calendar cal = DateFormatUtil.parseStrToCalendar(dateStr);
int lastDay = cal.getActualMaximum(Calendar.DAY_OF_WEEK);
cal.set(Calendar.DAY_OF_WEEK, lastDay);
return DateFormatUtil.formatDate(cal.getTime(),
DateFormatUtil.DATE_FORMAT);
}
/**
* 获取指定日期的周的第一天
* @param dateStr
* @return
* @throws Exception
*/
public static String firstDay(String dateStr) throws Exception{
if (dateStr == null) {
return null;
}
Calendar cal = Calendar.getInstance();
SimpleDateFormat sf = new SimpleDateFormat(DATE_FORMAT);
Date date = convertStringToDate(dateStr);
cal.setTime(date);
int day_of_week = cal.get(Calendar.DAY_OF_WEEK) - 2;
cal.add(Calendar.DATE, -day_of_week);
return sf.format(cal.getTime());
}
/**
* 获取指定日期的周的最后一天
*
*/
public static String lastDay(String dateStr)throws Exception{
if (dateStr==null) {
return null;
}
Calendar cal = Calendar.getInstance();
SimpleDateFormat sf = new SimpleDateFormat(DATE_FORMAT);
cal.setTime(convertStringToDate(dateStr));
cal.add(Calendar.DATE, 6);
return sf.format(cal.getTime());
}
public static String firstMonth(String dateStr)throws Exception{
if (dateStr==null) {
return null;
}
Calendar cal = Calendar.getInstance();
SimpleDateFormat sf = new SimpleDateFormat(DATE_FORMAT);
cal.setTime(convertStringToDate(dateStr));
cal.set(GregorianCalendar.DAY_OF_MONTH, 1);
return sf.format(cal.getTime());
}
/**
* 获取本月第最后一天
* @param dateStr
* @return
* @throws Exception
*/
public static String lastMonth(String dateStr) throws Exception{
if (dateStr==null) {
return null;
}
Calendar cal = Calendar.getInstance();
SimpleDateFormat sf = new SimpleDateFormat(DATE_FORMAT);
cal.setTime(convertStringToDate(dateStr));
cal.set( Calendar.DATE, 1 );
cal.roll(Calendar.DATE, - 1 );
return sf.format(cal.getTime());
}
/**
* 获取当前月份所在季度
* @param dateStr
* @return
* @throws Exception
*/
public static Map<String,String> getSeason(String dateStr) throws Exception{
if (dateStr==null) {
return null;
}
Map<String,String> map = new HashMap<String,String>();
String array[][] = {{"01","03"},{"04","06"},{"07","09"},{"10","12"}};
SimpleDateFormat month = new SimpleDateFormat("MM");
SimpleDateFormat year = new SimpleDateFormat("yyyy");
Date date = convertStringToDate(dateStr);
int season=Integer.valueOf (month.format(date));
String years = year.format(date);
String beginSeason = null;
String endSeason = null;
if (season>=1&&season<=3) {
beginSeason = array[0][0];
endSeason = array[0][1];
}
if (season>=4&&season<=6) {
beginSeason = array[1][0];
endSeason = array[1][1];
}
if (season>=7&&season<=9) {
beginSeason = array[2][0];
endSeason = array[2][1];
}
if (season>=10&&season<=12) {
beginSeason = array[3][0];
endSeason = array[3][1];
}
map.put("beginSeason", years+"-"+beginSeason);
map.put("endSeason", years+"-"+endSeason);
return map;
}
/**
* 比较两个日期相差的天数
*
* @param fDate
* @param oDate
* @return
*/
public static int getIntervalDays(Date fDate, Date oDate) {
if (null == fDate || null == oDate) {
return -1;
}
long intervalMilli = oDate.getTime() - fDate.getTime();
return (int) (intervalMilli / (24 * 60 * 60 * 1000));
}
/**
* 比较2个时间相差的分钟数
*
* @param fDate
* @param oDate
* @return
*/
public static int getIntervalMinutes(Date fDate, Date oDate){
if (null == fDate || null == oDate) {
return -1;
}
long intervalMilli = oDate.getTime() - fDate.getTime();
return (int) (intervalMilli / (60 * 1000));
}
/**
* 获得一个月的最后一天
* @param date 指定日期
* @return 该月的最后一天
*/
protected Date getLastDayOfMonth(Date date)
{
Date tempDate = DateUtils.truncate(date, Calendar.DATE);
Calendar cal = DateUtils.toCalendar(tempDate);
cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));
return cal.getTime();
}
/**
* 获得一个月的第一天
* @param date 指定日期
* @return 该月的最后一天
*/
protected Date getFirstDayOfMonth(Date date)
{
Date tempDate = DateUtils.truncate(date, Calendar.DATE);
return DateUtils.setDays(tempDate, 1);
}
/**
* 获得某个日期指定的一天
* @param date 指定日期
* @return 该月的最后一天
*/
protected Date getCustomDay(Date date, int day)
{
Date tempDate = DateUtils.truncate(date, Calendar.DATE);
return DateUtils.setDays(tempDate, day);
}
}[/code]