JAVA工具類(1) --Java日期函數大全(日期比較大小,日期相減,日期相加,擷取年份等)

來源:互聯網
上載者:User
package com.gcloud.common;import org.apache.http.util.TextUtils;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.regex.Pattern;/** * 日期時間工具類 * Created by charlin on 2017/9/3. */public class DateUtil {    public static final String CHINA_DATE_FORMAT = "yyyy年MM月dd日";    public static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";    public static final String DATE_FORMAT = "yyyy-MM-dd";    public static final String TIME_FORMAT = "HH:mm:ss";    //----------------判斷-----------------------------------------------    /**     * 是否是潤年     * @param yearNum     * @return     */    public static boolean isLeapYear(int yearNum) {        boolean isLeep = false;        if ((yearNum % 4 == 0) && (yearNum % 100 != 0))            isLeep = true;        else if (yearNum % 400 == 0)            isLeep = true;        else {            isLeep = false;        }        return isLeep;    }    /**     * 判斷是否是日期     *     * @param date     * @return     */    public static boolean isDate(String date) {        //判斷年月日的Regex,接受輸入格式為2010-12-24,可接受平年閏年的日期        String regex = "(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)";        Pattern pattern = Pattern.compile(regex);        return pattern.matcher(date).matches();    }    /**     * 驗證是不是生日     *     * @param birthday     * @return     */    public static boolean verifyBirthDay(String birthday) {        if (TextUtils.isEmpty(birthday)) return false;        if (!birthday.contains("-")) return false;        String[] arr = birthday.split("-");        if (null == arr || arr.length != 3 || arr[0].length() != 4 || arr[1].length() != 2 || arr[2].length() != 2)            return false;        int year = getYear(new Date());        int birthYear = Integer.parseInt(arr[0]);        if (birthYear <= 1900 || birthYear > year) return false;        String curDate = formatDate(new Date(), DATE_FORMAT);        if (birthday.compareTo(curDate) > 0) return false;        return isDate(birthday);    }    //-------------------自動轉化--------------------------------------------    /**     * 把字串自動轉化為時間格式     *     * @param dateStr     * @return     */    public static Date parseDateByAuto(String dateStr) {        if (StringUtil.isEmpty(dateStr)) {            return null;        }        String format = DATE_FORMAT;        if (dateStr.indexOf("/") > -1) {            format = format.replace("-", "/");        }        if (dateStr.indexOf(":") != -1) {            format += " HH:mm";        }        //存在秒        if (dateStr.indexOf(":") != dateStr.lastIndexOf(":")) {            format += ":ss";        }        return parseDate(dateStr, format);    }    /**     * 自動識別格式     * @param date     * @return     */    public static String formatDateByAuto(Date date){        String format = DATE_FORMAT;        if( !(date instanceof java.sql.Date) && (date.getSeconds()>0||date.getMinutes()>0||date.getHours()>0)){            format = DATETIME_FORMAT;        }        return formatDate(date, format);    }    //------------當前日期與時間 --------------------------------    /**取當前日期*/    public static Date getCurrDate() {return parseDate(formatDate(new Date())); }    /**取目前時間*/    public static Date getCurrDateTime() {return parseDate(formatDate(new Date())); }    /**取當前日期*/    public static String getCurrDateStr() { return formatDate(new Date());    }    /**取目前時間*/    public static String getCurrDateTimeStr() { return formatDate(new Date(), DATETIME_FORMAT);}    public static String formatCurrDate() {return formatDate(new Date(),DATE_FORMAT); }    public static String formatCurrDateTime() {return formatDate(new Date(),DATETIME_FORMAT);}    public static String formatCurrDateToS(String strFormat) {return formatDate(new Date(), strFormat); }    //-----------時間計算--------------------------------------------    /**     * 時間相減     * @param strDateBegin     * @param strDateEnd     * @param iType     * @return     */    public static int getDiffDate(String strDateBegin, String strDateEnd, int iType) {        Calendar calBegin = Calendar.getInstance();        calBegin.setTime(parseDate(strDateBegin, DATETIME_FORMAT));        Calendar calEnd = Calendar.getInstance();        calBegin.setTime(parseDate(strDateEnd, DATETIME_FORMAT));        long lBegin = calBegin.getTimeInMillis();        long lEnd = calEnd.getTimeInMillis();        if (iType == Calendar.SECOND)            return (int) ((lEnd - lBegin) / 1000L);        if (iType == Calendar.MINUTE)            return (int) ((lEnd - lBegin) / 60000L);        if (iType == Calendar.HOUR)            return (int) ((lEnd - lBegin) / 3600000L);        if (iType == Calendar.DAY_OF_MONTH) {            return (int) ((lEnd - lBegin) / 86400000L);        }        return -1;    }    /**     * 添加天數或月份或年得到新的時間     *     * @param strDate     * @param count     * @param dayType Calendar.YEAR     * @return     */    public static String getAddDateTime(String strDate, int count, int dayType) {        Calendar cal = Calendar.getInstance();        cal.setTime(parseDate(strDate));        cal.add(dayType, count);        SimpleDateFormat sdf = null;        if ((dayType == Calendar.YEAR) || (dayType == Calendar.MONTH) || (dayType == Calendar.DAY_OF_MONTH))            sdf = new SimpleDateFormat(DATE_FORMAT);        else            sdf = new SimpleDateFormat(DATETIME_FORMAT);        return sdf.format(cal.getTime());    }    /**     * 日期增加天數     * @param date     * @param iCount     * @return     */    public static Date getAddDate(Date date, int iCount) {        Calendar cal = Calendar.getInstance();        cal.setTime(date);        cal.add(Calendar.DAY_OF_MONTH, iCount);        return cal.getTime();    }    /**     * 比較日期     *     * @param dateStr1     * @param dateStr2     * @return     */    public static int compareDate(String dateStr1, String dateStr2) {        Date date1 = parseDate(dateStr1);        Date date2 = parseDate(dateStr2);        if (date1.getTime() > date2.getTime())            return -1;        else if (date1.getTime() < date2.getTime())            return 1;        else            return 0;    }    public static int compareDate(Date date1, Date date2) {        if (date1.getTime() > date2.getTime())            return -1;        else if (date1.getTime() < date2.getTime())            return 1;        else            return 0;    }    /**     * 時間差     *     * @param startDate     * @param endDate     * @return     */    public static int getDiffDays(Date startDate, Date endDate) {        int days = 0;        if (startDate.after(endDate)) {            Date temp = startDate;            startDate = endDate;            endDate = temp;        }        days = (int) (endDate.getTime() - startDate.getTime()) / 1000 * 60 * 60 * 24;        return days;    }    /**     * 當前日期的後幾天     *     * @param date     * @param n     * @return     */    public static Date getAfterDay(Date date, int n) {        Calendar c = Calendar.getInstance();        c.setTime(date);        c.add(Calendar.DATE, n);        return c.getTime();    }    //---------擷取時間天數----------------------------------------------    /**     * 擷取當前月的最後一天     *     * @param dateStr     * @return     */    public static String getMonthEnd(String dateStr) {        //當前第一天        Date date = parseDate(getMonthBegin(dateStr));        Calendar c = Calendar.getInstance();        c.setTime(date);        c.add(Calendar.MONTH, 1);        c.add(Calendar.DAY_OF_YEAR, -1);        return formatDate(c.getTime());    }    public static String getMonthEnd(Date date) {        Calendar c = Calendar.getInstance();        c.setTime(date);        c.set(Calendar.DATE, c.getActualMaximum(Calendar.DATE));        return formatDate(c.getTime());    }    /**     * 獲得當前日期的月份第一天     *     * @param dateStr     * @return     */    public static String getMonthBegin(String dateStr) {        Date date = parseDate(dateStr);        return formatDate(date, "yyyy-MM") + 01;    }    public static String getMonthBegin(Date date) {        return formatDate(date, "yyyy-MM") + 01;    }    //--------------格式化日期-----------------------------------------    /**     * 格式化日期為字串     *     * @param date     * @param format     * @return     */    public static String formatDate(Date date, String format) {        return new SimpleDateFormat(format).format(date);    }    public static String formatDate(Date date) {        return formatDate(date, DATE_FORMAT);    }    public static String formateChinaDate(Date date) {        return formatDate(date, CHINA_DATE_FORMAT);    }    public static String formateDateTime(Date date) {        return formatDate(date, DATETIME_FORMAT);    }    public static String formateTime(Date date) {        return formatDate(date, TIME_FORMAT);    }    //-----------------格式化字串為日期--------------------------------------    /**     * 格式化字串為日期     *     * @param date     * @param format     * @return     */    public static Date parseDate(String date, String format) {        try {            return new SimpleDateFormat(format).parse(date);        } catch (ParseException e) {            e.printStackTrace();        }        return null;    }    public static Date parseDate(String date) { return parseDate(date, DATE_FORMAT);}    public static Date parseChinaDate(String date) {        return parseDate(date, CHINA_DATE_FORMAT);    }    public static Date parseDateTime(String date) {        return parseDate(date, DATETIME_FORMAT);    }    public static Date parseTime(String date) {        return parseDate(date, TIME_FORMAT);    }    //---擷取年月日時分秒----------------------------------------------------    /**     * 擷取年份     *     * @param date     * @return     */    public static int getYear(Date date) {        Calendar c = Calendar.getInstance();        c.setTime(date);        return c.get(Calendar.YEAR);    }    /**     * 擷取月份     *     * @param date     * @return     */    public static int getMonth(Date date) {        Calendar c = Calendar.getInstance();        c.setTime(date);        return c.get(Calendar.MONTH) + 1;    }    /**     * 擷取日     *     * @param date     * @return     */    public static int getDay(Date date) {        Calendar c = Calendar.getInstance();        c.setTime(date);        return c.get(Calendar.DAY_OF_MONTH);    }    /**     * 擷取星期     *     * @param date     * @return     */    public static int getWeek(Date date) {        Calendar c = Calendar.getInstance();        c.setTime(date);        return c.get(Calendar.DAY_OF_WEEK);    }    /**     * 擷取時間     *     * @param date     * @return     */    public static int getHour(Date date) {        Calendar c = Calendar.getInstance();        c.setTime(date);        return c.get(Calendar.HOUR_OF_DAY);    }    /**     * 擷取分種     *     * @param date     * @return     */    public static int getMinute(Date date) {        Calendar c = Calendar.getInstance();        c.setTime(date);        return c.get(Calendar.MINUTE);    }    /**     * 擷取秒     *     * @param date     * @return     */    public static int getSecond(Date date) {        Calendar c = Calendar.getInstance();        c.setTime(date);        return c.get(Calendar.SECOND);    }    //--------------擷取星期幾---------------------------------------------------    /**     * 擷取星期幾     *     * @param strDate     * @return     */    public static String getWeekDayName(String strDate) {        String[] mName = {"日", "一", "二", "三", "四", "五", "六"};        Date date = parseDate(strDate);        int week = getWeek(date);        return "星期" + mName[week];    }    public static String getWeekDayName(Date date) {        String[] mName = {"日", "一", "二", "三", "四", "五", "六"};        int week = getWeek(date);        return "星期" + mName[week];    }    /**     * 一年中的星期幾     * @return     */    public static int getWeekNumOfYear(Date date) {        Calendar calendar = Calendar.getInstance();        calendar.setTime(date);        return calendar.get(Calendar.WEEK_OF_YEAR);    }    public static int getWeekNumOfYear(String date) {        Calendar calendar = Calendar.getInstance();        calendar.setTime(parseDate(date, DATE_FORMAT));        return calendar.get(Calendar.WEEK_OF_YEAR);    }    /**     * 擷取本周星期一的日期     * @param yearNum     * @param weekNum     * @return     * @throws ParseException     */    public static String getYearWeekFirstDay(int yearNum, int weekNum)  {        Calendar cal = Calendar.getInstance();        cal.set(Calendar.YEAR, yearNum);        cal.set(Calendar.WEEK_OF_YEAR, weekNum);        cal.set(Calendar.DAY_OF_WEEK, 2);        String tempYear = Integer.toString(yearNum);        String tempMonth = Integer.toString(cal.get(Calendar.MONTH) + 1);        String tempDay = Integer.toString(cal.get(Calendar.DAY_OF_MONTH)-1);        return tempYear + "-" + tempMonth + "-" + tempDay;    }    /**     *  擷取本周星期天的日期     * @param yearNum     * @param weekNum     * @return     * @throws ParseException     */    public static String getYearWeekEndDay(int yearNum, int weekNum)  {        Calendar cal = Calendar.getInstance();        cal.set(Calendar.YEAR, yearNum);        cal.set(Calendar.WEEK_OF_YEAR, weekNum + 1);        cal.set(Calendar.DAY_OF_WEEK, 1);        String tempYear = Integer.toString(yearNum);        String tempMonth = Integer.toString(cal.get(Calendar.MONTH) + 1);        String tempDay = Integer.toString(cal.get(Calendar.DAY_OF_MONTH)-1);        return tempYear + "-" + tempMonth + "-" + tempDay;    }    //--------------擷取天數---------------------------------------------------    /**     * 擷取某年某月的第一天     * @param yearNum     * @param monthNum     * @return     */    public static Date getYearMonthFirstDay(int yearNum, int mon

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.