JAVA日期时间常用工具类

记录一下常用的时间工具类

1. 创建时间格式枚举

类似于常量定义,方便使用

package com.zhh.util.dateutil;
/**
 * 时间字符串格式枚举
 * 
 */
public enum DateFormatter {
	
    /**
     *将日期格式化为日期/时间字符串,或者从给定字符串的开头解析文本,生成格式为“yyyy-MM-dd”的日期 
     */
    Year_To_Day("yyyy-MM-dd"),
    Year_To_Hour("yyyy-MM-dd HH"),
    Year_To_Minute("yyyy-MM-dd HH:mm"),
    /**
     *将日期格式化为日期/时间字符串,或从给定字符串的开头解析文本,生成格式为“yyyy-MM-dd HH:mm:ss”的日期 
     */
    Year_To_Second("yyyy-MM-dd HH:mm:ss"),
    Year_To_Millisecond("yyyy-MM-dd HH:mm:ss.SSS"),
    YearToDay("yyyyMMdd"),
    YearToHour("yyyyMMddHH"),
    YearToMinute("yyyyMMddHHmm"),
    YearToSecond("yyyyMMddHHmmss"),
    YearToMillisecond("yyyyMMddHHmmssSSS");

    private String pattern = "";

    private DateFormatter(String pattern) {
        this.pattern = pattern;
    }

    @Override
    public String toString() {
        return this.pattern;
    }

    public String value() {
        return this.pattern;
    }
}

2. 创建时间转换工具类

 

package com.zhh.util.dateutil;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;

/**
 * 时间工具类
 * @author zhaoheng
 */
public class DateUtil {
	/**
	 * 一天的秒数
	 */
	public static final int DATE_TIMEMILLIONS = 86400;
	
    /**
     * 根据formatter指定的日期格式,日期转换字符串
     *
     * @param date 时间、日期
     * @param dateFormatter 字符串格式 例如:yyyy-MM-dd
     * @return
     */
    public static String formatDateToString(Date date, DateFormatter dateFormatter) {
        if (null == date || null == dateFormatter) {
            return "";
        }

        DateFormat dateFormat = new SimpleDateFormat(dateFormatter.value());

        return dateFormat.format(date);
    }

    /**
     * 根据formatter指定的日期格式,字符串转换日期
     *
     * @param date	时间
     * @param dateFormatter 字符串格式
     * @return Date
     * @throws ParseException
     */
    public static Date formatStringToDate(String date, DateFormatter dateFormatter) throws ParseException {
        if (null == date || null == dateFormatter || "".equals(date)) {
            return null;
        }

        DateFormat dateFormat = new SimpleDateFormat(dateFormatter.value());

        return dateFormat.parse(date.replaceAll("/", "-"));
    }

    /**
     * 根据formatter指定的日期格式,字符串转换日期
     *
     * @param date
     * @param dateFormatter
     * @return Date
     * @throws ParseException
     */
    public static Date formatDateToDate(Date date, DateFormatter dateFormatter) throws ParseException {
        if (null == date || null == dateFormatter) {
            return null;
        }

        DateFormat dateFormat = new SimpleDateFormat(dateFormatter.value());

        return dateFormat.parse(dateFormat.format(date));
    }

    /**
     * 两个时间之间的天数差(结束时间小于开始时间就是负数)
     *
     * @param date1 开始时间
     * @param date2 结束时间
     * @param isRoundUp 有余数时是否按一天计算
     * @return
     */
    public static Integer daysBetweenDates(Date date1, Date date2, boolean isRoundUp) {
        if (null == date1 || null == date2) {
            return null;
        }

        int days = (int) ((date1.getTime() - date2.getTime()) / 86400000);
        int mod = (int) ((date1.getTime() - date2.getTime()) % 86400000);

        if (isRoundUp && mod > 0) {
            days = days + 1;
        }

        return days;
    }
    
    /**
     * 两个时间之间的天数差(天数差绝对值,没有负值)
     *
     * @param date1
     * @param date2
     * @param isRoundUp 有余数时是否按一天计算
     * @return
     */
    public static Integer daysBetweenDatesByAbsolute(Date date1, Date date2, boolean isRoundUp) {
        if (null == date1 || null == date2) {
            return null;
        }

        int days = Math.abs((int) ((date1.getTime() - date2.getTime()) / 86400000));
        int mod = Math.abs((int) ((date1.getTime() - date2.getTime()) % 86400000));

        if (isRoundUp && mod > 0) {
            days = days + 1;
        }

        return days;
    }
    
    /**
     * 使用给定字段年、月、日获取日期。
     *
     * @param year 月
     * @param month 日
     * @param day 天
     * @return
     */
    public static Date date(int year, int month, int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, day, 0, 0, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        return calendar.getTime();
    }

    /**
     * 使用给定字段年、月、日、小时获取日期(24小时制).
     *
     * @param year	年
     * @param month	月
     * @param day	日
     * @param hour  (24小时制)
     * @return
     */
    public static Date date(int year, int month, int day, int hour) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, day, hour, 0, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        return calendar.getTime();
    }

    /**
     * 使用给定的日期字段的一年,月,日,小时(24小时制),分钟
     *
     * @param year	年
     * @param month	月
     * @param day	日
     * @param hour   (24小时制)
     * @param minute	分
     * @return
     */
    public static Date date(int year, int month, int day, int hour, int minute) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, day, hour, minute, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        return calendar.getTime();
    }

    /**
     * Gets a date using the given fields year,month,day,hour(24小时制),minute,second.
     *
     * @param year	年
     * @param month	月
     * @param day	日
     * @param hour   (24小时制)
     * @param minute	分
     * @param second	秒
     * @return
     */
    public static Date date(int year, int month, int day, int hour, int minute, int second) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, day, hour, minute, second);
        calendar.set(Calendar.MILLISECOND, 0);

        return calendar.getTime();
    }

    /**
     * 比较两个时间是否相等
     *
     * @param date1
     * @param date2
     * @param dateFormatter 比较维度,如:Year_To_Day比较年月日;Year_To_Second比较年月日时分秒
     * @return
     */
    public static boolean isTwoDateEquals(Date date1, Date date2, DateFormatter dateFormatter) {
        Date nowDate = new Date();

        if (null == date1) {
            date1 = nowDate;
        }

        if (null == date2) {
            date2 = nowDate;
        }

        String dateStr1 = formatDateToString(date1, dateFormatter);
        String dateStr2 = formatDateToString(date2, dateFormatter);

        if (dateStr1 == dateStr2 || dateStr1.equals(dateStr2)) {
            return true;
        }

        return false;
    }

    /**
     * 判断年份是否为闰年
     *
     * @param year
     * @return
     */
    public static boolean isLeapYear(int year) {
        return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
    }

    /**
     * 判断时间区间是否包含闰年(只计算是否包含2.29)
     *
     * @param startDate
     * @param endDate
     * @return
     */
    public static boolean isContainLeapYear(Date startDate, Date endDate) {

        if (startDate == null || endDate == null) {
            return false;
        }

        Calendar startTime = Calendar.getInstance();
        Calendar endTime = Calendar.getInstance();
        startTime.setTime(startDate);
        endTime.setTime(endDate);

        int startDay = startTime.get(Calendar.DAY_OF_YEAR);
        int endDay = endTime.get(Calendar.DAY_OF_YEAR);
        int startYear = startTime.get(Calendar.YEAR);
        int endYear = endTime.get(Calendar.YEAR);

        if (isLeapYear(startYear) && startDay <= 60 && (endDay >= 60 || startYear != endYear)) {
            return true;
        } else if (isLeapYear(endYear) && endDay >= 60 && (startDay <= 60 || startYear != endYear)) {
            return true;
        } else {
            return false;
        }

    }

    /**
     * 判断时间格式是否正确
     * 
     * @param strDate
     * @return
     */
    public static boolean isValidDate(String strDate) {
        boolean convertSuccess = true;
        // 指定日期格式为四位年/两位月份/两位日期,注意yyyy/MM/dd区分大小写;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        if (StringUtils.isNotBlank(strDate)) {
            try {
                // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
                format.setLenient(false);
                format.parse(strDate);
            } catch (ParseException e) {
                // e.printStackTrace();
                // 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
                convertSuccess = false;
            }
        } else {
            convertSuccess = false;
        }
        return convertSuccess;
    }

    /**
     * 将yyyy年MM月DD日转成yyyy-mm-dd
     */
    public static String formatStrToString(String str) {
        if (StringUtils.isNotBlank(str)) {
            if (str.indexOf("年") > 0 && str.indexOf("月") > 0 && str.indexOf("日") > 0) {
                str = str.substring(0, str.indexOf("年")) + "-"
                        + str.substring(str.indexOf("年") + 1, str.indexOf("月")) + "-"
                        + str.substring(str.indexOf("月") + 1, str.indexOf("日"));
            }
        }
        return str;
    }
    
    /**
     * 时间转指定格式字符串
     * @param date	时间
     * @param format 格式 例如 yyyy-MM-dd HH:mm:ss
     * @return
     */
    
	public static String dateToString(Date date,String format){
		String timeString="";
		if(date==null)
		{
			date=new Date();
		}
		if(format==null || format.trim().equals(""))
		{
			format="yyyy-MM-dd HH:mm:ss";
		}
		SimpleDateFormat sf = new SimpleDateFormat(format.trim());
		timeString=sf.format(date);			
		return timeString;
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章