Java时间处理工具类

写的比较乱,凑合看哈

/**
 * Created by AlexWong on 2016/10/26.
 */
@Component
public class DateUtils {

    private final Logger logger = Logger.getLogger(DateUtils.class);

    private static String defaultDatePattern = null;
    private String timePattern = "HH:mm";
    private Calendar cale = Calendar.getInstance();
    public static final String TS_FORMAT = DateUtils.getDatePattern() + " HH:mm:ss.S";
    /** 日期格式yyyy-MM字符串常量 */
    private final String MONTH_FORMAT = "yyyy.MM";
    /** 日期格式yyyy-MM-dd字符串常量 */
    public final String DATE_FORMAT = "yyyy-MM-dd";
    private final String DATE_FORMAT2 = "yyyy.MM.dd";
    /** 日期格式HH:mm:ss字符串常量 */
    private final String HOUR_FORMAT = "HH:mm:ss";
    /** 日期格式yyyy-MM-dd HH:mm:ss字符串常量 */
    private final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    /** 某天开始时分秒字符串常量  00:00:00 */
    public final String DAY_BEGIN_STRING_HHMMSS = " 00:00:00";
    /**  某天结束时分秒字符串常量  23:59:59  */
    public final String DAY_END_STRING_HHMMSS = " 23:59:59";
    public final String GMT8 = "GMT+8";
    public final String UTC = "UTC";
    private SimpleDateFormat sdf_month_format = new SimpleDateFormat(MONTH_FORMAT);
    private SimpleDateFormat sdf_date_format = new SimpleDateFormat(DATE_FORMAT);
    private SimpleDateFormat sdf_date_format2 = new SimpleDateFormat(DATE_FORMAT2);
    private SimpleDateFormat sdf_date_format3 = new SimpleDateFormat(DATE_FORMAT+DAY_END_STRING_HHMMSS);
    private SimpleDateFormat sdf_hour_format = new SimpleDateFormat(HOUR_FORMAT);
    private SimpleDateFormat sdf_datetime_format = new SimpleDateFormat(DATETIME_FORMAT);

    /**
     * 获得服务器当前日期及时间,以格式为:yyyy-MM-dd HH:mm:ss的日期字符串形式返回
     * 
     * 
     * @return
     */
    public String getDateTime() {
        try {
            return sdf_datetime_format.format(cale.getTime());
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 获得服务器当前日期,以格式为:yyyy-MM-dd的日期字符串形式返回
     * 
     * 
     * @return
     */
    public String getDate() {
        try {
            return sdf_date_format.format(cale.getTime());
        } catch (Exception e) {
            logger.error("",e);
            return "";
        }
    }

    /**
     * 获得服务器当前日期,以格式为:yyyy-MM-dd的日期字符串形式返回
     *
     *
     * @return
     */
    public String getDate(int i) {
        try {
            if (i==0) {
                SimpleDateFormat sdf_date_format = new SimpleDateFormat(DATE_FORMAT+DAY_BEGIN_STRING_HHMMSS);
                return sdf_date_format.format(cale.getTime());
            } else {
                SimpleDateFormat sdf_date_format = new SimpleDateFormat(DATE_FORMAT+DAY_END_STRING_HHMMSS);
                return sdf_date_format.format(cale.getTime());
            }
        } catch (Exception e) {
            logger.error("",e);
            return "";
        }
    }

    /**
     * 获得服务器当前时间,以格式为:HH:mm:ss的日期字符串形式返回
     * 
     * 
     * @return
     */
    public String getTime() {
        String temp = " ";
        try {
            temp += sdf_hour_format.format(cale.getTime());
            return temp;
        } catch (Exception e) {
            logger.error("",e);
            return "";
        }
    }

    /**
     * 统计时开始日期的默认值
     * 
     * 
     * @return
     */
    public String getStartDate() {
        try {
            return getYear() + "-01-01";
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 统计时结束日期的默认值
     * 
     * 
     * @return
     */
    public String getEndDate() {
        try {
            return getDate();
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 获得服务器当前日期的年份
     * 
     * 
     * @return
     */
    public String getYear() {
        try {
            return String.valueOf(cale.get(Calendar.YEAR));
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 获得服务器当前日期的月份
     * 
     * 
     * @return
     */
    public String getMonth() {
        try {
            java.text.DecimalFormat df = new java.text.DecimalFormat();
            df.applyPattern("00;00");
            return df.format((cale.get(Calendar.MONTH) + 1));
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 获得服务器在当前月中天数
     * 
     * 
     * @return
     */
    public String getDay() {
        try {
            return String.valueOf(cale.get(Calendar.DAY_OF_MONTH));
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 比较两个日期相差的天数
     * 
     * 
     * @param date1
     * @param date2
     * @return
     */
    public int getMargin(String date1, String date2) {
        int margin;
        try {
            ParsePosition pos = new ParsePosition(0);
            ParsePosition pos1 = new ParsePosition(0);
            Date dt1 = sdf_date_format.parse(date1, pos);
            Date dt2 = sdf_date_format.parse(date2, pos1);
            long l = dt1.getTime() - dt2.getTime();
            margin = (int) (l / (24 * 60 * 60 * 1000));
            return margin;
        } catch (Exception e) {
            return 0;
        }
    }

    public int compare_date(String DATE1, String DATE2) {
        DateFormat df = new SimpleDateFormat(DATETIME_FORMAT);
        try {
            Date dt1 = df.parse(DATE1);
            Date dt2 = df.parse(DATE2);
            if (dt1.getTime() > dt2.getTime()) {
                return 1;
            } else if (dt1.getTime() < dt2.getTime()) {
                return -1;
            } else {
                return 0;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return 0;
    }

    /**
     * 比较两个日期相差的天数
     * 
     * 
     * @param date1
     * @param date2
     * @return
     */
    public double getDoubleMargin(String date1, String date2) {
        double margin;
        try {
            ParsePosition pos = new ParsePosition(0);
            ParsePosition pos1 = new ParsePosition(0);
            Date dt1 = sdf_datetime_format.parse(date1, pos);
            Date dt2 = sdf_datetime_format.parse(date2, pos1);
            long l = dt1.getTime() - dt2.getTime();
            margin = (l / (24 * 60 * 60 * 1000.00));
            return margin;
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 比较两个日期相差的月数
     * 
     * 
     * @param date1
     * @param date2
     * @return
     */
    public int getMonthMargin(String date1, String date2) {
        int margin;
        try {
            margin = (Integer.parseInt(date2.substring(0, 4)) - Integer.parseInt(date1.substring(0, 4))) * 12;
            margin += (Integer.parseInt(date2.substring(4, 7).replaceAll("-0",
                    "-")) - Integer.parseInt(date1.substring(4, 7).replaceAll("-0", "-")));
            return margin;
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 返回日期加X天后的日期
     * 
     * 
     * @param date
     * @param i
     * @return
     */
    public String addDay(String date, int i) {
        try {
            GregorianCalendar gCal = new GregorianCalendar(
                    Integer.parseInt(date.substring(0, 4)),
                    Integer.parseInt(date.substring(5, 7)) - 1,
                    Integer.parseInt(date.substring(8, 10)));
            gCal.add(GregorianCalendar.DATE, i);
            return sdf_date_format.format(gCal.getTime());
        } catch (Exception e) {
            return getDate();
        }
    }

    /**
     * 返回日期加X天后的日期
     *
     *
     * @param date
     * @param i
     * @return
     */
    public String addDayToDateTime(String date, int i, int type) {
        try {
            GregorianCalendar gCal = new GregorianCalendar(
                    Integer.parseInt(date.substring(0, 4)),
                    Integer.parseInt(date.substring(5, 7)) - 1,
                    Integer.parseInt(date.substring(8, 10)));
            gCal.add(GregorianCalendar.DATE, i);
            if (type==1) {
                return sdf_date_format3.format(gCal.getTime());
            } else {
                return sdf_datetime_format.format(gCal.getTime());
            }
        } catch (Exception e) {
            return getDate();
        }
    }

    public String addDayPoint(String date, int i) {
        try {
            GregorianCalendar gCal = new GregorianCalendar(
                    Integer.parseInt(date.substring(0, 4)),
                    Integer.parseInt(date.substring(5, 7)) - 1,
                    Integer.parseInt(date.substring(8, 10)));
            gCal.add(GregorianCalendar.DATE, i);
            return sdf_date_format2.format(gCal.getTime());
        } catch (Exception e) {
            return getDate();
        }
    }

    /**
     * 返回日期加X月后的日期
     * 
     * 
     * @param date
     * @param i
     * @return
     */
    public String addMonth(String date, int i) {
        try {
            GregorianCalendar gCal = new GregorianCalendar(
                    Integer.parseInt(date.substring(0, 4)),
                    Integer.parseInt(date.substring(5, 7)) - 1,
                    Integer.parseInt(date.substring(8, 10)));
            gCal.add(GregorianCalendar.MONTH, i);
            return sdf_month_format.format(gCal.getTime());
        } catch (Exception e) {
            return getDate();
        }
    }

    /**
     * 返回日期加X年后的日期
     * 
     * 
     * @param date
     * @param i
     * @return
     */
    public String addYear(String date, int i) {
        try {
            GregorianCalendar gCal = new GregorianCalendar(
                    Integer.parseInt(date.substring(0, 4)),
                    Integer.parseInt(date.substring(5, 7)) - 1,
                    Integer.parseInt(date.substring(8, 10)));
            gCal.add(GregorianCalendar.YEAR, i);
            return sdf_date_format.format(gCal.getTime());
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 返回某年某月中的最大天
     * 
     * 
     * @param iyear
     * @param imonth
     * @return
     */
    public int getMaxDay(int iyear, int imonth) {
        int day = 0;
        try {
            if (imonth == 1 || imonth == 3 || imonth == 5 || imonth == 7
                    || imonth == 8 || imonth == 10 || imonth == 12) {
                day = 31;
            } else if (imonth == 4 || imonth == 6 || imonth == 9 || imonth == 11) {
                day = 30;
            } else if ((0 == (iyear % 4)) && (0 != (iyear % 100)) || (0 == (iyear % 400))) {
                day = 29;
            } else {
                day = 28;
            }
            return day;
        } catch (Exception e) {
            return 1;
        }
    }

    /**
     * 格式化日期
     * 
     * 
     * @param orgDate
     * @param Type
     * @param Span
     * @return
     */
    @SuppressWarnings("static-access")
    public String rollDate(String orgDate, int Type, int Span) {
        try {
            String temp = "";
            int iyear, imonth, iday;
            int iPos = 0;
            char seperater = '-';
            if (orgDate == null || orgDate.length() < 6) {
                return "";
            }

            iPos = orgDate.indexOf(seperater);
            if (iPos > 0) {
                iyear = Integer.parseInt(orgDate.substring(0, iPos));
                temp = orgDate.substring(iPos + 1);
            } else {
                iyear = Integer.parseInt(orgDate.substring(0, 4));
                temp = orgDate.substring(4);
            }

            iPos = temp.indexOf(seperater);
            if (iPos > 0) {
                imonth = Integer.parseInt(temp.substring(0, iPos));
                temp = temp.substring(iPos + 1);
            } else {
                imonth = Integer.parseInt(temp.substring(0, 2));
                temp = temp.substring(2);
            }

            imonth--;
            if (imonth < 0 || imonth > 11) {
                imonth = 0;
            }

            iday = Integer.parseInt(temp);
            if (iday < 1 || iday > 31)
                iday = 1;

            Calendar orgcale = Calendar.getInstance();
            orgcale.set(iyear, imonth, iday);
            temp = this.rollDate(orgcale, Type, Span);
            return temp;
        } catch (Exception e) {
            return "";
        }
    }

    public String rollDate(Calendar cal, int Type, int Span) {
        try {
            String temp = "";
            Calendar rolcale;
            rolcale = cal;
            rolcale.add(Type, Span);
            temp = sdf_date_format.format(rolcale.getTime());
            return temp;
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 返回默认的日期格式
     * 
     * 
     * @return
     */
    public static synchronized String getDatePattern() {
        defaultDatePattern = "yyyy-MM-dd";
        return defaultDatePattern;
    }

    public static synchronized String getDateTimePattern() {
        defaultDatePattern = "yyyy-MM-dd HH:mm:ss";
        return defaultDatePattern;
    }

    /**
     * 将指定日期按默认格式进行格式代化成字符串后输出如:yyyy-MM-dd
     * 
     * 
     * @param aDate
     * @return
     */
    public final String getDate(Date aDate) {
        SimpleDateFormat df = null;
        String returnValue = "";
        if (aDate != null) {
            df = new SimpleDateFormat(getDatePattern());
            returnValue = df.format(aDate);
        }
        return (returnValue);
    }

    /**
     * 取得给定日期的时间字符串,格式为当前默认时间格式
     * 
     * 
     * @param theTime
     * @return
     */
    public String getTimeNow(Date theTime) {
        return getDateTime(timePattern, theTime);
    }

    /**
     * 取得当前时间的Calendar日历对象
     * 
     * 
     * @return
     * @throws Exception
     */
    public Calendar getToday() throws Exception {
        Date today = new Date();
        SimpleDateFormat df = new SimpleDateFormat(getDatePattern());
        String todayAsString = df.format(today);
        Calendar cal = new GregorianCalendar();
        cal.setTime(convertStringToDate(todayAsString));
        return cal;
    }

    /**
     * 将日期类转换成指定格式的字符串形式
     * 
     * 
     * @param aMask
     * @param aDate
     * @return
     */
    public final String getDateTime(String aMask, Date aDate) {
        SimpleDateFormat df = null;
        String returnValue = "";

        if (aDate == null) {
        } else {
            df = new SimpleDateFormat(aMask);
            returnValue = df.format(aDate);
        }
        return (returnValue);
    }

    /**
     * 将指定的日期转换成默认格式的字符串形式
     * 
     * 
     * @param aDate
     * @return
     */
    public final String convertDateToString(Date aDate) {
        return getDateTime(getDatePattern(), aDate);
    }

    public final String convertDateTimeToString(Date aDate) {
        return getDateTime(getDateTimePattern(), aDate);
    }

    /**
     * 将日期字符串按指定格式转换成日期类型
     * 
     * 
     * @param aMask 指定的日期格式,如:yyyy-MM-dd
     * @param strDate 待转换的日期字符串
     * @return
     * @throws ParseException
     */
    public final Date convertStringToDate(String aMask, String strDate)
            throws ParseException {
        SimpleDateFormat df = null;
        Date date = null;
        df = new SimpleDateFormat(aMask);

        try {
            date = df.parse(strDate);
        } catch (ParseException pe) {
            throw pe;
        }
        return (date);
    }

    /**
     * 将日期字符串按默认格式转换成日期类型
     * 
     * 
     * @param strDate
     * @return
     * @throws ParseException
     */
    public Date convertStringToDate(String strDate)
            throws ParseException {
        Date aDate = null;

        try {
            aDate = convertStringToDate(getDatePattern(), strDate);
        } catch (ParseException pe) {
            throw new ParseException(pe.getMessage(), pe.getErrorOffset());
        }
        return aDate;
    }

    /**
     * 返回一个JAVA简单类型的日期字符串
     * 
     * 
     * @return
     */
    public String getSimpleDateFormat() {
        SimpleDateFormat formatter = new SimpleDateFormat();
        String NDateTime = formatter.format(new Date());
        return NDateTime;
    }

    /**
     * 将指定字符串格式的日期与当前时间比较
     * @author DYLAN
     * @date Feb 17, 2012
     * @param strDate 需要比较时间
     * @return
     *      <p>
     *      int code
     *      <ul>
     *      <li>-1 当前时间 < 比较时间 </li>
     *      <li> 0 当前时间 = 比较时间 </li>
     *      <li>>=1当前时间 > 比较时间 </li>
     *      </ul>
     *      </p>
     */
    public int compareToCurTime (String strDate) {
        if (StringUtils.isBlank(strDate)) {
            return -1;
        }
        Date curTime = cale.getTime();
        String strCurTime = null;
        try {
            strCurTime = sdf_datetime_format.format(curTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (StringUtils.isNotBlank(strCurTime)) {
            return strCurTime.compareTo(strDate);
        }
        return -1;
    }

    /**
     * 为查询日期添加最小时间
     *
     * @param
     * @return
     */
    @SuppressWarnings("deprecation")
    public Date addStartTime(Date param) {
        Date date = param;
        try {
            date.setHours(0);
            date.setMinutes(0);
            date.setSeconds(0);
            return date;
        } catch (Exception ex) {
            return date;
        }
    }

    /**
     * 为查询日期添加最大时间
     *
     * @param
     * @return
     */
    @SuppressWarnings("deprecation")
    public Date addEndTime(Date param) {
        Date date = param;
        try {
            date.setHours(23);
            date.setMinutes(59);
            date.setSeconds(0);
            return date;
        } catch (Exception ex) {
            return date;
        }
    }

    /**
     * 返回系统现在年份中指定月份的天数
     *
     * @param
     * @return 指定月的总天数
     */
    @SuppressWarnings("deprecation")
    public String getMonthLastDay(int month) {
        Date date = new Date();
        int[][] day = { { 0, 30, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
                { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } };
        int year = date.getYear() + 1900;
        if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
            return day[1][month] + "";
        } else {
            return day[0][month] + "";
        }
    }

    /**
     * 返回指定年份中指定月份的天数
     *
     * @year 年份year
     * @month 月份month
     * @return 指定月的总天数
     */
    public String getMonthLastDay(int year, int month) {
        int[][] day = { { 0, 30, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
                { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } };
        if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
            return day[1][month] + "";
        } else {
            return day[0][month] + "";
        }
    }

    /**
     * 判断是平年还是闰年
     * 
     * 
     * @param year
     * @return
     */
    public boolean isLeapyear(int year) {
        if ((year % 4 == 0 && year % 100 != 0) || (year % 400) == 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 取得当前时间的日戳
     * 
     * 
     * @return
     */
    @SuppressWarnings("deprecation")
    public String getTimestamp() {
        Date date = cale.getTime();
        String timestamp = "" + (date.getYear() + 1900) + date.getMonth()
                + date.getDate() + date.getMinutes() + date.getSeconds()
                + date.getTime();
        return timestamp;
    }

    public List<String> getListDateString(String startDate, String endDate) {
        List<String> listDate = Lists.newArrayList();
        int count = getMonthMargin(endDate, startDate);
        for (int i=count; i>=0; i--) {
            listDate.add( addMonth(startDate, i));
        }
        return listDate;
    }

    /**
     * 取得指定时间的日戳
     *
     * @return
     */
    @SuppressWarnings("deprecation")
    public String getTimestamp(Date date) {
        String timestamp = "" + (date.getYear() + 1900) + date.getMonth()
                + date.getDate() + date.getMinutes() + date.getSeconds()
                + date.getTime();
        return timestamp;
    }

    /**
     * 取得指定时间的日戳
     *
     * @return
     */
    @SuppressWarnings("deprecation")
    public String getTimestamp(String strDate) throws Exception{
        Date date = convertStringToDate(strDate);
        String timestamp = "" + (date.getYear() + 1900) + date.getMonth()
                + date.getDate() + date.getMinutes() + date.getSeconds()
                + date.getTime();
        return timestamp;
    }

    public void main(String[] args) {
        System.out.println(getYear() + "|" + getMonth() + "|" + getDate());
    }

    public String getUTCTimeZoneTime(String strDate ) throws Exception{
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
        Date date = convertStringToDate(DATETIME_FORMAT, strDate);
        TimeZone srcTimeZone = TimeZone.getTimeZone(GMT8);
        TimeZone destTimeZone = TimeZone.getTimeZone(GMT8);

        return dateTransformBetweenTimeZone(date, formatter, srcTimeZone, destTimeZone);
    }

    public String dateTransformBetweenTimeZone(Date sourceDate, DateFormat formatter,
                                               TimeZone sourceTimeZone, TimeZone targetTimeZone) {
        Long targetTime = sourceDate.getTime() - sourceTimeZone.getRawOffset() + targetTimeZone.getRawOffset();
        return getTime(new Date(targetTime), formatter);
    }

    public String getTime(Date date, DateFormat formatter){
        return formatter.format(date);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值