日期时间处理工具类_java常用的时间处理工具-程序员宅基地

技术标签: Java  算法  java  开发语言  

  • Java版本,通用的日期、时间处理工具类(本工具类的部分功能):
    • 计算当前时间几小时之后的时间
    • 计算当前时间几分钟之后的时间.
    • 添加指定秒数
    • 判断输入的字符串是否为合法的小时.
    • 判断输入的字符串是否为合法的分或秒.
    • 取得新的日期.
    • 获取明天日期
    • 取得“X年X月X日”的日期格式.
    • 取得两个日期间隔秒数(日期1-日期2)
    • 取得两个日期的间隔天数.
    • 判断表示时间的字符是否为符合yyyyMMddHHmmss格式.
    • 获取系统日期的前一天日期,返回Date.
    • 获得指定时间当天起点时间
    • 获得指定时间本周起点时间.
    • 获得指定时间本月起点时间.
    • 获得指定时间下月起点时间.
    • 获得指定时间本年度起点时间.
    • 获得指定时间本年度起点时间.
    • 判断参date上min分钟后,是否小于当前时间.
    • 是否在现在时间之前.
    • 判断两个日期是否是同一天.
    • 获取系统当前时间.
    • 获取当前时间的前几天或者后几天的日期.
    • 获取JAVA的月份值和对应字符串的列表
    • 进行日期多语言处理
public class DateUtil {
    

    /**
     * The Constant log.
     */
    private static final Logger log = LoggerFactory.getLogger(DateUtil.class);

    /**
     * The Constant ONE_DAY_SECONDS.
     */
    public static final long ONE_DAY_SECONDS = 86400;

    public static final long ONE_MINUTE_SECONDS = 60;

    public static final long ONE_MINUTE_MILL_SECONDS = 60000;

    public static final long ONE_MONTH_SECONDS = 2592000;

    /**
     * The Constant MONTHS_OF_ONE_QUARTER.
     */
    public static final int MONTHS_OF_ONE_QUARTER = 3;

    /**
     * The Constant MONTHS_OF_ONE_YEAR.
     */
    public static final int MONTHS_OF_ONE_YEAR = 12;

    public static final long TEN_SECONDS_MILLSECONDS = 10000;
    /*
     * private static DateFormat dateFormat = null; private static DateFormat
     * longDateFormat = null; private static DateFormat dateWebFormat = null;
     */
    /**
     * The Constant YEAR_Format.
     */
    public static final String YEAR_FORMAT = "yyyy";

    /**
     * The Constant shortFormat.
     */
    public static final String shortFormat = "yyyyMMdd";

    /**
     * The Constant shortFormat.
     */
    public static final String YEAR_MONTH_Format = "yyyyMM";

    /**
     * The Constant longFormat.
     */
    public static final String longFormat = "yyyyMMddHHmmss";

    public static final String longLongFormat = "yyyyMMddHHmmssSSS";

    /**
     * The Constant webFormat.
     */
    public static final String ymdFormat = "yyyy-MM-dd";

    public static final String ymdFormat2 = "yyyy/MM/dd";

    /**
     * The Constant timeFormat.
     */
    public static final String timeFormat = "HHmmss";

    public static final String timeFormat2 = "HH:mm:ss";

    /**
     * The Constant monthFormat.
     */
    public static final String monthFormat = "yyyyMM";

    public static final String pointDtFormat = "yyyy.MM.dd";

    /**
     * The Constant chineseDtFormat.
     */
    public static final String chineseDtFormat = "yyyy年MM月dd日";

    public static final String fullFormat = "yyyy-MM-dd HH:mm:ss.SSS";

    public static final String fullFormatWithSixMill = "yyyy-MM-dd HH:mm:ss.SSSSSS";
    /**
     * The Constant newFormat.
     */
    public static final String noMillionSecondFormat = "yyyy-MM-dd HH:mm:ss";

    public static final String sqlFormat = "yyyy-MM-dd HH:mm:ss.SSS";
    /**
     * The Constant noSecondFormat.
     */
    public static final String noSecondFormat = "yyyy-MM-dd HH:mm";

    /**
     * The Constant newFormat.
     */
    public static final String tx0TimeFormat = "yyyy/MM/dd HH:mm:ss";

    /**
     * The Constant ONE_DAY_MILL_SECONDS.
     */
    public static final long ONE_DAY_MILL_SECONDS = 86400000;

    /**
     * The Enum TimeUnitEnum.
     */
    public enum TimeUnitEnum {
    

        /**
         * The month.
         */
        MONTH("月"),
        /**
         * The quarter.
         */
        QUARTER("季度"),
        /**
         * The year.
         */
        YEAR("年");

        /**
         * The message.
         */
        private String message;

        /**
         * Instantiates a new time unit enum.
         *
         * @param message the message
         */
        TimeUnitEnum(String message) {
    
            this.message = message;
        }

        /**
         * Convert to months.
         *
         * @param quantity the quantity
         * @param timeUnit the time unit
         * @return the integer
         */
        public static Integer convertToMonths(int quantity, String timeUnit) {
    

            Integer months = 0;
            if (timeUnit.equalsIgnoreCase("月")) {
    
                months = quantity;
            } else if (timeUnit.equalsIgnoreCase("季度")) {
    
                months = quantity * DateUtil.MONTHS_OF_ONE_QUARTER;

            } else if (timeUnit.equalsIgnoreCase("年")) {
    
                months = quantity * DateUtil.MONTHS_OF_ONE_YEAR;
            }
            return months;
        }

        /*
         * (non-Javadoc)
         *
         * @see java.lang.Enum#toString()
         */
        @Override
        public String toString() {
    
            return this.message;
        }
    }

    /**
     * Gets the new date format.
     *
     * @param pattern the pattern
     * @return the new date format
     */
    public static DateFormat getNewDateFormat(String pattern) {
    
        DateFormat df = new SimpleDateFormat(pattern);

        df.setLenient(false);
        return df;
    }

    /**
     * Format.
     *
     * @param date the date
     * @param format the format
     * @return the string
     */
    public static String format(Date date, String format) {
    
        if (date == null) {
    
            return null;
        }

        return new SimpleDateFormat(format).format(date);
    }

    /**
     * Parses the date no time.
     *
     * @param sDate the s date
     * @return the date
     * @throws ParseException the parse exception
     */
    public static Date parseDateNoTime(String sDate) throws ParseException {
    
        DateFormat dateFormat = new SimpleDateFormat(shortFormat);

        if ((sDate == null) || (sDate.length() < shortFormat.length())) {
    
            throw new ParseException("length too little", 0);
        }

        if (!StringUtils.isNumeric(sDate)) {
    
            throw new ParseException("not all digit", 0);
        }

        return dateFormat.parse(sDate);
    }

    /**
     * Parses the date no time.
     *
     * @param sDate the s date
     * @param format the format
     * @return the date
     * @throws ParseException the parse exception
     */
    public static Date parseDate(String sDate, String format) throws ParseException {
    
        if (StringUtils.isBlank(format)) {
    
            throw new ParseException("Null format. ", 0);
        }

        DateFormat dateFormat = new SimpleDateFormat(format);

        if ((sDate == null) || (sDate.length() < format.length())) {
    
            throw new ParseException("length too little", 0);
        }

        return dateFormat.parse(sDate);
    }

    /**
     * Parses the date no time with delimit.
     *
     * @param sDate the s date
     * @param delimit the delimit
     * @return the date
     * @throws ParseException the parse exception
     */
    public static Date parseDateNoTimeWithDelimit(String sDate, String delimit) throws ParseException {
    
        sDate = sDate.replaceAll(delimit, "");

        DateFormat dateFormat = new SimpleDateFormat(shortFormat);

        if ((sDate == null) || (sDate.length() != shortFormat.length())) {
    
            throw new ParseException("length not match", 0);
        }

        return dateFormat.parse(sDate);
    }

    /**
     * Parses the date long format.
     *
     * @param sDate the s date
     * @return the date
     */
    public static Date parseDateLongFormat(String sDate) {
    
        DateFormat dateFormat = new SimpleDateFormat(longFormat);
        Date d = null;

        if ((sDate != null) && (sDate.length() == longFormat.length())) {
    
            try {
    
                d = dateFormat.parse(sDate);
            } catch (ParseException ex) {
    
                return null;
            }
        }

        return d;
    }

    /**
     * Parses the date new format.
     *
     * @param sDate the s date
     * @return the date
     */
    public static Date parseDateNewFormat(String sDate) {
    
        DateFormat dateFormat = new SimpleDateFormat(noMillionSecondFormat);
        Date d = null;
        if ((sDate != null) && (sDate.length() == noMillionSecondFormat.length())) {
    
            try {
    
                d = dateFormat.parse(sDate);
            } catch (ParseException ex) {
    
                return null;
            }
        }
        return d;
    }

    /**
     * Parses the date new format.
     *
     * @param sDate the s date
     * @return the date
     */
    public static Date parseDateNewFormatForXj(String sDate) {
    
        DateFormat dateFormat = new SimpleDateFormat(noMillionSecondFormat);
        Date d = null;
        if ((sDate != null)) {
    
            try {
    
                d = dateFormat.parse(sDate);
            } catch (ParseException ex) {
    
                return null;
            }
        }
        return d;
    }

    public static Date parseDateWithymdFormat(String sDate) {
    
        DateFormat dateFormat = new SimpleDateFormat(ymdFormat);
        Date d = null;
        if ((sDate != null)) {
    
            try {
    
                d = dateFormat.parse(sDate);
            } catch (ParseException ex) {
    
                return null;
            }
        }
        return d;
    }

    public static Date parseDateFullFormat(String sDate) {
    
        DateFormat dateFormat = new SimpleDateFormat(fullFormat);
        Date d = null;
        if ((sDate != null)) {
    
            try {
    
                d = dateFormat.parse(sDate);
            } catch (ParseException ex) {
    
                return null;
            }
        }
        return d;
    }

    /**
     * Parses the year format.
     *
     * @param sDate the s date
     * @return the date
     */
    public static Date parseYearFormat(String sDate) {
    
        DateFormat dateFormat = new SimpleDateFormat(YEAR_FORMAT);
        Date d = null;
        if ((sDate != null) && (sDate.length() == YEAR_FORMAT.length())) {
    
            try {
    
                d = dateFormat.parse(sDate);
            } catch (ParseException ex) {
    
                return null;
            }
        }
        return d;
    }

    public static Long parseYMDHMSDateToStamp(Date date) throws ParseException {
    
        long ts = date.getTime();
        return ts;
    }

    /*
     * 将时间戳转换为时间
     */
    public static Date parseStampToDate(String s) {
    
        if (StringUtil.isBlank(s)) {
    
            return null;
        }
        Long timestamp = Long.parseLong(s);
        String date = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date(timestamp));
        // res = simpleDateFormat.format(date);
        return parseDateNewFormat(date);

    }

    /*
     * 将时间戳转换为时间
     */
    public static Date parseStampToDate(Long timestamp) {
    
        if (timestamp == null) {
    
            return null;
        }
        if (timestamp.toString().length()==10){
    
            timestamp=timestamp*1000;
        }
        String date = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
            .format(new java.util.Date(timestamp));
        return parseDateNewFormat(date);
    }

    public static String parseStampToDate(String s, String format) {
    
        if (StringUtil.isBlank(s)) {
    
            return null;
        }
        Long timestamp = Long.parseLong(s);
        String date = new java.text.SimpleDateFormat(format).format(new java.util.Date(timestamp));
        // res = simpleDateFormat.format(date);
        return date;

    }

    /**
     * 计算当前时间几小时之后的时间.
     *
     * @param date the date
     * @param hours the hours
     * @return the date
     */
    public static Date addHours(Date date, long hours) {
    
        return addMinutes(date, hours * 60);
    }

    /**
     * 计算当前时间几分钟之后的时间.
     *
     * @param date the date
     * @param minutes the minutes
     * @return the date
     */
    public static Date addMinutes(Date date, long minutes) {
    
        return addSeconds(date, minutes * 60);
    }

    /**
     * Adds the seconds.
     *
     * @param date1 the date1
     * @param secs the secs
     * @return the date
     */

    public static Date addSeconds(Date date1, long secs) {
    
        return new Date(date1.getTime() + (secs * 1000));
    }

    /**
     * 判断输入的字符串是否为合法的小时.
     *
     * @param hourStr the hour str
     * @return true/false
     */
    public static boolean isValidHour(String hourStr) {
    
        if (!StringUtils.isEmpty(hourStr) && StringUtils.isNumeric(hourStr)) {
    
            int hour = new Integer(hourStr).intValue();

            if ((hour >= 0) && (hour <= 23)) {
    
                return true;
            }
        }

        return false;
    }

    /**
     * 判断输入的字符串是否为合法的分或秒.
     *
     * @param str the str
     * @return true/false
     */
    public static boolean isValidMinuteOrSecond(String str) {
    
        if (!StringUtils.isEmpty(str) && StringUtils.isNumeric(str)) {
    
            int hour = new Integer(str).intValue();

            if ((hour >= 0) && (hour <= 59)) {
    
                return true;
            }
        }

        return false;
    }

    /**
     * 取得新的日期.
     *
     * @param date1 日期
     * @param days 天数
     * @return 新的日期
     */
    public static Date addDays(Date date1, long days) {
    
        return addSeconds(date1, days * ONE_DAY_SECONDS);
    }

    /**
     * Gets the tomorrow date string.
     *
     * @param sDate the s date
     * @return the tomorrow date string
     * @throws ParseException the parse exception
     */
    public static String getTomorrowDateString(String sDate) throws ParseException {
    
        Date aDate = parseDateNoTime(sDate);

        aDate = addSeconds(aDate, ONE_DAY_SECONDS);

        return getDateString(aDate);
    }

    /**
     * Gets the tomorrow web date.
     *
     * @param sDate the s date
     * @return the tomorrow web date
     * @throws ParseException the parse exception
     */
    public static String getTomorrowWebDate(String sDate) throws ParseException {
    
        String tomorrowShortDate = getTomorrowDateString(convertWeb2ShortFormat(sDate));

        return convert2WebFormat(tomorrowShortDate);
    }

    /**
     * Gets the long date string.
     *
     * @param date the date
     * @return the long date string
     */
    public static String getLongDateString(Date date) {
    
        DateFormat dateFormat = new SimpleDateFormat(longFormat);

        return getDateString(date, dateFormat);
    }

    /**
     * Gets the new format date string.
     *
     * @param date the date
     * @return the new format date string
     */
    public static String getNewFormatDateString(Date date) {
    
        DateFormat dateFormat = new SimpleDateFormat(noMillionSecondFormat);
        return getDateString(date, dateFormat);
    }

    public static String getFullFormatDateString(Date date) {
    
        DateFormat dateFormat = new SimpleDateFormat(fullFormat);
        return getDateString(date, dateFormat);
    }

    public static String getFullFormatWithSixMillDateString(Date date) {
    
        DateFormat dateFormat = new SimpleDateFormat(fullFormatWithSixMill);
        return getDateString(date, dateFormat);
    }

    /**
     * Gets the date string.
     *
     * @param date the date
     * @param dateFormat the date format
     * @return the date string
     */
    public static String getDateString(Date date, DateFormat dateFormat) {
    
        if (date == null || dateFormat == null) {
    
            return null;
        }

        return dateFormat.format(date);
    }

    /**
     * Gets the yester day date string.
     *
     * @param sDate the s date
     * @return the yester day date string
     * @throws ParseException the parse exception
     */
    public static String getYesterDayDateString(String sDate) throws ParseException {
    
        Date aDate = parseDateNoTime(sDate);

        aDate = addSeconds(aDate, -ONE_DAY_SECONDS);

        return getDateString(aDate);
    }

    /**
     * Gets the date string.
     *
     * @param date the date
     * @return 当天的时间格式化为"yyyyMMdd"
     */
    public static String getDateString(Date date) {
    
        DateFormat df = getNewDateFormat(shortFormat);

        return df.format(date);
    }

    /**
     * Gets the web date string.
     *
     * @param date the date
     * @return the web date string
     */
    public static String getWebDateString(Date date) {
    
        DateFormat format = getNewDateFormat(ymdFormat);

        return getDateString(date, format);
    }

    /**
     * Gets the no second date string.
     *
     * @param date the date
     * @return the no second date string
     */
    public static String getNoSecondDateString(Date date) {
    
        DateFormat dateFormat = getNewDateFormat(noSecondFormat);

        return getDateString(date, dateFormat);
    }

    /**
     * 取得“X年X月X日”的日期格式.
     *
     * @param date the date
     * @return the chinese date string
     */
    public static String getChineseDateString(Date date) {
    
        DateFormat dateFormat = getNewDateFormat(chineseDtFormat);

        return getDateString(date, dateFormat);
    }

    /**
     * Gets the today string.
     *
     * @return the today string
     */
    public static String getTodayString() {
    
        DateFormat dateFormat = getNewDateFormat(shortFormat);

        return getDateString(new Date(), dateFormat);
    }

    public static String getTodayLongString() {
    
        DateFormat dateFormat = getNewDateFormat(noMillionSecondFormat);

        return getDateString(new Date(), dateFormat);
    }

    public static Date getTodayLongFormat() {
    
        Date d = null;
        DateFormat dateFormat = getNewDateFormat(noMillionSecondFormat);
        String time = getDateString(new Date(), dateFormat);
        d = parseDateNewFormat(time);
        return d;
    }

    /**
     * Gets the time string.
     *
     * @param date the date
     * @return the time string
     */
    public static String getTimeString(Date date) {
    
        DateFormat dateFormat = getNewDateFormat(timeFormat);

        return getDateString(date, dateFormat);
    }

    /**
     * Gets the before day string.
     *
     * @param days the days
     * @return the before day string
     */
    public static String getBeforeDayString(int days) {
    
        Date date = new Date(System.currentTimeMillis() - (ONE_DAY_MILL_SECONDS * days));
        DateFormat dateFormat = getNewDateFormat(shortFormat);

        return getDateString(date, dateFormat);
    }

    /**
     * 取得两个日期间隔秒数(日期1-日期2).
     *
     * @param one 日期1
     * @param two 日期2
     * @return 间隔秒数
     */
    public static long getDiffSeconds(Date one, Date two) {
    
        Calendar sysDate = new GregorianCalendar();

        sysDate.setTime(one);

        Calendar failDate = new GregorianCalendar();

        failDate.setTime(two);
        return (sysDate.getTimeInMillis() - failDate.getTimeInMillis()) / 1000;
    }

    /**
     * Gets the diff minutes.
     *
     * @param one the one
     * @param two the two
     * @return the diff minutes
     */
    public static long getDiffMinutes(Date one, Date two) {
    
        Calendar sysDate = new GregorianCalendar();

        sysDate.setTime(one);

        Calendar failDate = new GregorianCalendar();

        failDate.setTime(two);
        return (sysDate.getTimeInMillis() - failDate.getTimeInMillis()) / (60 * 1000);
    }

    /**
     * 取得两个日期的间隔天数.
     *
     * @param one the one
     * @param two the two
     * @return 间隔天数
     */
    public static long getDiffDays(Date one, Date two) {
    
        Calendar sysDate = new GregorianCalendar();

        sysDate.setTime(one);

        Calendar failDate = new GregorianCalendar();

        failDate.setTime(two);
        return (sysDate.getTimeInMillis() - failDate.getTimeInMillis()) / (24 * 60 * 60 * 1000);
    }

    /**
     * Gets the before day string.
     *
     * @param dateString the date string
     * @param days the days
     * @return the before day string
     */
    public static String getBeforeDayString(String dateString, int days) {
    
        Date date;
        DateFormat df = getNewDateFormat(shortFormat);

        try {
    
            date = df.parse(dateString);
        } catch (ParseException e) {
    
            date = new Date();
        }

        date = new Date(date.getTime() - (ONE_DAY_MILL_SECONDS * days));

        return df.format(date);
    }

    /**
     * Checks if is valid short date format.
     *
     * @param strDate the str date
     * @return true, if is valid short date format
     */
    public static boolean isValidShortDateFormat(String strDate) {
    
        if (strDate.length() != shortFormat.length()) {
    
            return false;
        }

        try {
    
            Integer.parseInt(strDate); // ---- 避免日期中输入非数字 ----
        } catch (Exception NumberFormatException) {
    
            return false;
        }

        DateFormat df = getNewDateFormat(shortFormat);

        try {
    
            df.parse(strDate);
        } catch (ParseException e) {
    
            return false;
        }

        return true;
    }

    /**
     * Checks if is valid short date format.
     *
     * @param strDate the str date
     * @param delimiter the delimiter
     * @return true, if is valid short date format
     */
    public static boolean isValidShortDateFormat(String strDate, String delimiter) {
    
        String temp = strDate.replaceAll(delimiter, "");

        return isValidShortDateFormat(temp);
    }

    /**
     * 判断表示时间的字符是否为符合yyyyMMddHHmmss格式.
     *
     * @param strDate the str date
     * @return true, if is valid long date format
     */
    public static boolean isValidLongDateFormat(String strDate) {
    
        if (strDate.length() != longFormat.length()) {
    
            return false;
        }

        try {
    
            Long.parseLong(strDate); // ---- 避免日期中输入非数字 ----
        } catch (Exception NumberFormatException) {
    
            return false;
        }

        DateFormat df = getNewDateFormat(longFormat);

        try {
    
            df.parse(strDate);
        } catch (ParseException e) {
    
            return false;
        }

        return true;
    }

    /**
     * 判断表示时间的字符是否为符合yyyyMMddHHmmss格式.
     *
     * @param strDate the str date
     * @param delimiter the delimiter
     * @return true, if is valid long date format
     */
    public static boolean isValidLongDateFormat(String strDate, String delimiter) {
    
        String temp = strDate.replaceAll(delimiter, "");

        return isValidLongDateFormat(temp);
    }

    /**
     * Gets the short date string.
     *
     * @param strDate the str date
     * @return the short date string
     */
    public static String getShortDateString(String strDate) {
    
        return getShortDateString(strDate, "-|/");
    }

    /**
     * Gets the short date string.
     *
     * @param strDate the str date
     * @param delimiter the delimiter
     * @return the short date string
     */
    public static String getShortDateString(String strDate, String delimiter) {
    
        if (StringUtils.isBlank(strDate)) {
    
            return null;
        }

        String temp = strDate.replaceAll(delimiter, "");

        if (isValidShortDateFormat(temp)) {
    
            return temp;
        }

        return null;
    }

    /**
     * Gets the short first day of month.
     *
     * @return the short first day of month
     */
    public static String getShortFirstDayOfMonth() {
    
        Calendar cal = Calendar.getInstance();
        Date dt = new Date();

        cal.setTime(dt);
        cal.set(Calendar.DAY_OF_MONTH, 1);

        DateFormat df = getNewDateFormat(shortFormat);

        return df.format(cal.getTime());
    }

    /**
     * Gets the web today string.
     *
     * @return the web today string
     */
    public static String getWebTodayString() {
    
        DateFormat df = getNewDateFormat(ymdFormat);

        return df.format(new Date());
    }

    /**
     * Gets the web first day of month.
     *
     * @return the web first day of month
     */
    public static String getWebFirstDayOfMonth() {
    
        Calendar cal = Calendar.getInstance();
        Date dt = new Date();

        cal.setTime(dt);
        cal.set(Calendar.DAY_OF_MONTH, 1);

        DateFormat df = getNewDateFormat(ymdFormat);

        return df.format(cal.getTime());
    }

    /**
     * Convert.
     *
     * @param dateString the date string
     * @param formatIn the format in
     * @param formatOut the format out
     * @return the string
     */
    public static String convert(String dateString, DateFormat formatIn, DateFormat formatOut) {
    
        try {
    
            Date date = formatIn.parse(dateString);

            return formatOut.format(date);
        } catch (ParseException e) {
    
            log.warn("convert() --- orign date error: " + dateString);
            return "";
        }
    }

    /**
     * Convert web2 short format.
     *
     * @param dateString the date string
     * @return the string
     */
    public static String convertWeb2ShortFormat(String dateString) {
    
        DateFormat df1 = getNewDateFormat(ymdFormat);
        DateFormat df2 = getNewDateFormat(shortFormat);

        return convert(dateString, df1, df2);
    }

    /**
     * Convert2 web format.
     *
     * @param dateString the date string
     * @return the string
     */
    public static String convert2WebFormat(String dateString) {
    
        dateString = StringUtils.defaultIfBlank(dateString, "");
        DateFormat df1 = getNewDateFormat(shortFormat);
        DateFormat df2 = getNewDateFormat(ymdFormat);

        return convert(dateString, df1, df2);
    }

    /**
     * Convert2 chinese dt format.
     *
     * @param dateString the date string
     * @return the string
     */
    public static String convert2ChineseDtFormat(String dateString) {
    
        DateFormat df1 = getNewDateFormat(shortFormat);
        DateFormat df2 = getNewDateFormat(chineseDtFormat);

        return convert(dateString, df1, df2);
    }

    /**
     * Convert from web format.
     *
     * @param dateString the date string
     * @return the string
     */
    public static String convertFromWebFormat(String dateString) {
    
        DateFormat df1 = getNewDateFormat(shortFormat);
        DateFormat df2 = getNewDateFormat(ymdFormat);

        return convert(dateString, df2, df1);
    }

    /**
     * Web date not less than.
     *
     * @param date1 the date1
     * @param date2 the date2
     * @return true, if successful
     */
    public static boolean webDateNotLessThan(String date1, String date2) {
    
        DateFormat df = getNewDateFormat(ymdFormat);

        return dateNotLessThan(date1, date2, df);
    }

    /**
     * Date not less than.
     *
     * @param date1 the date1
     * @param date2 the date2
     * @param format the format
     * @return true, if successful
     */
    public static boolean dateNotLessThan(String date1, String date2, DateFormat format) {
    
        try {
    
            Date d1 = format.parse(date1);
            Date d2 = format.parse(date2);

            if (d1.before(d2)) {
    
                return false;
            } else {
    
                return true;
            }
        } catch (ParseException e) {
    
            log.debug("dateNotLessThan() --- ParseException(" + date1 + ", " + date2 + ")");
            return false;
        }
    }

    /**
     * Gets the email date.
     *
     * @param today the today
     * @return the email date
     */
    public static String getEmailDate(Date today) {
    
        String todayStr;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");

        todayStr = sdf.format(today);
        return todayStr;
    }

    /**
     * Gets the sms date.
     *
     * @param today the today
     * @return the sms date
     */
    public static String getSmsDate(Date today) {
    
        String todayStr;
        SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日HH:mm");

        todayStr = sdf.format(today);
        return todayStr;
    }

    /**
     * Format time range.
     *
     * @param startDate the start date
     * @param endDate the end date
     * @param format the format
     * @return the string
     */
    public static String formatTimeRange(Date startDate, Date endDate, String format) {
    
        if ((endDate == null) || (startDate == null)) {
    
            return null;
        }

        String rt = null;
        long range = endDate.getTime() - startDate.getTime();
        long day = range / DateUtils.MILLIS_PER_DAY;
        long hour = (range % DateUtils.MILLIS_PER_DAY) / DateUtils.MILLIS_PER_HOUR;
        long minute = (range % DateUtils.MILLIS_PER_HOUR) / DateUtils.MILLIS_PER_MINUTE;

        if (range < 0) {
    
            day = 0;
            hour = 0;
            minute = 0;
        }

        rt = format.replaceAll("dd", String.valueOf(day));
        rt = rt.replaceAll("hh", String.valueOf(hour));
        rt = rt.replaceAll("mm", String.valueOf(minute));

        return rt;
    }

    /**
     * Format month.
     *
     * @param date the date
     * @return the string
     */
    public static String formatMonth(Date date) {
    
        if (date == null) {
    
            return null;
        }

        return new SimpleDateFormat(monthFormat).format(date);
    }

    /**
     * 获取系统日期的前一天日期,返回Date.
     *
     * @return the before date
     */
    public static Date getBeforeDate() {
    
        Date date = new Date();

        return new Date(date.getTime() - (ONE_DAY_MILL_SECONDS));
    }

    /**
     * 获得指定时间当天起点时间.
     *
     * @param date the date
     * @return date
     */
    public static Date getDayBegin(Date date) {
    
        Calendar calendar = GregorianCalendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    /**
     * Gets the day end.
     *
     * @param date the date
     * @return the day end
     */
    public static Date getDayEnd(Date date) {
    
        Calendar calendar = GregorianCalendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return calendar.getTime();
    }

    /**
     * 获得指定时间本周起点时间.
     *
     * @param date date
     * @return date
     */
    public static Date getWeekBegin(Date date) {
    
        Calendar calendar = GregorianCalendar.getInstance();
        calendar.setTime(getDayBegin(date));
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        return calendar.getTime();
    }

    /**
     * 获得指定时间本月起点时间.
     *
     * @param date date
     * @return date
     */
    public static Date getMonthBegin(Date date) {
    
        Calendar calendar = GregorianCalendar.getInstance();
        calendar.setTime(getDayBegin(date));
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        return calendar.getTime();
    }

    /**
     * 获得指定时间下月起点时间.
     *
     * @param date date
     * @return date
     */
    public static Date getNextMonthBegin(Date date) {
    
        Calendar calendar = GregorianCalendar.getInstance();
        calendar.setTime(getDayBegin(date));
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        int thisMonth = calendar.get(Calendar.MONTH);
        if (thisMonth != 11) {
    
            thisMonth += 1;
        } else {
    
            thisMonth = 0;
        }
        calendar.set(Calendar.MONTH, thisMonth);
        return calendar.getTime();
    }

    /**
     * 获得指定时间本年度起点时间.
     *
     * @param date date
     * @return date
     */
    public static Date getYearBegin(Date date) {
    
        Calendar calendar = GregorianCalendar.getInstance();
        calendar.setTime(getDayBegin(date));
        calendar.set(Calendar.DAY_OF_YEAR, 1);
        return calendar.getTime();
    }

    /**
     * 获得指定时间本年度起点时间.
     *
     * @param date date
     * @return date
     */
    public static Date getYearEnd(Date date) {
    
        Calendar calendar = GregorianCalendar.getInstance();
        calendar.setTime(getDayEnd(date));
        calendar.set(Calendar.MONTH, 11);
        calendar.set(Calendar.DAY_OF_MONTH, 31);
        return calendar.getTime();
    }

    /**
     * 判断参date上min分钟后,是否小于当前时间.
     *
     * @param date the date
     * @param min the min
     * @return true, if successful
     */
    public static boolean dateLessThanNowAddMin(Date date, long min) {
    
        return addMinutes(date, min).before(new Date());

    }

    /**
     * 是否在现在时间之前.
     *
     * @param date the date
     * @return true, if is before now
     */
    public static boolean isBeforeNow(Date date) {
    
        if (date == null) {
    
            return false;
        }
        return date.compareTo(new Date()) < 0;
    }

    /**
     * 是否有效.
     *
     * @param requestTime 请求时间
     * @param effectTime 生效时间
     * @param expiredTime 失效时间
     * @return true, if is validate
     */
    public static boolean isValidate(Date requestTime, Date effectTime, Date expiredTime) {
    
        if (requestTime == null || effectTime == null || expiredTime == null) {
    
            return false;
        }
        return effectTime.compareTo(requestTime) <= 0 && expiredTime.compareTo(requestTime) >= 0;
    }

    /**
     * The main method.
     *
     * @param args the arguments
     */
    public static void main(String[] args) {
    
        System.out.println("[" + convert2WebFormat(null) + "]");
    }

    /**
     * Parses the no second format.
     *
     * @param sDate the s date
     * @return the date
     * @throws ParseException the parse exception
     */
    public static Date parseNoSecondFormat(String sDate) throws ParseException {
    
        DateFormat dateFormat = new SimpleDateFormat(noSecondFormat);

        if ((sDate == null) || (sDate.length() < noSecondFormat.length())) {
    
            throw new ParseException("length too little", 0);
        }

        if (!StringUtils.isNumeric(sDate)) {
    
            throw new ParseException("not all digit", 0);
        }

        return dateFormat.parse(sDate);
    }

    /**
     * 判断两个日期是否是同一天.
     *
     * @param date1 the date1
     * @param date2 the date2
     * @return true, if is same day
     */
    public static boolean isSameDay(Date date1, Date date2) {
    
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(ymdFormat);
        return sdf.format(date1).equals(sdf.format(date2));
    }

    /**
     * 获取系统当前时间.
     *
     * @return the current ts
     */
    public static Date getCurrentTS() {
    
        Calendar calendar = Calendar.getInstance();
        Date date = calendar.getTime();
        return date;
    }

    /**
     * @return unix时间戳, unit sec
     */
    public static long getCurrentUnixTS() {
    
        return (long) (getCurrentTS().getTime() * 0.001);
    }

    /**
     * 获取系统当前时间.
     *
     * @return date
     */
    @Deprecated
    public static Date getWeekBefore() {
    
        Calendar calendar = Calendar.getInstance();
        Date date = calendar.getTime();
        return date;
    }

    /**
     * 获取当前时间的前几天或者后几天的日期.
     *
     * @param days the days
     * @return the date near current
     */
    public static Date getDateNearCurrent(int days) {
    
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, days);
        Date date = calendar.getTime();
        return date;

    }

    /**
     * Adds the months.
     *
     * @param date date
     * @param months 几个月
     * @return date
     */
    public static Date addMonths(Date date, int months) {
    
        Calendar calendar = GregorianCalendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, months);
        return calendar.getTime();
    }

    /**
     * 获取JAVA的月份值和对应字符串的列表
     */
    public static Map<Integer, String> getMonthList() {
    
        Map<Integer, String> map = new HashMap<Integer, String>();
        for (int i = 0; i < 12; i++) {
    
            map.put(i, String.valueOf(i + 1) + "月");
        }
        return map;

    }

    /**
     * 进行日期多语言处理
     */
    public static String dateFormateByLocale(String dateStr, Locale locale) {
    
        SimpleDateFormat format = null;
        Date date = new Date();
        try {
    
            if (locale == Locale.GERMAN) {
    
                format = new SimpleDateFormat("dd. MMMM yyyy", Locale.GERMAN);
            } else if (locale == Locale.ITALY) {
    
                format = new SimpleDateFormat("dd MMMM yyyy", Locale.ITALY);
                dateStr = dateStr.toUpperCase();
            } else if (locale == Locale.FRANCE) {
    
                format = new SimpleDateFormat("dd MMMM yyyy", Locale.FRANCE);
                dateStr = dateStr.toUpperCase();
            } else if (locale == Locale.JAPAN) {
    
                format = new SimpleDateFormat("yyyy'年'MM'月'dd'日'", Locale.JAPAN);
            } else if (locale == Locale.CANADA) {
    
                format = new SimpleDateFormat("MMMM dd, yyyy", Locale.CANADA);
            } else if (locale == Locale.CHINA) {
    
                format = new SimpleDateFormat("yyyy'年'MM'月'dd'日'", Locale.CHINA);
            } else {
    
                format = new SimpleDateFormat("MMMM dd, yyyy", Locale.US);
            }
            date = format.parse(dateStr);
        } catch (Exception ex) {
    
            log.error("format Error() ");
            return  dateStr;
        }

        return format.format(date);
    }

}

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/yudaxiaye/article/details/132338191

智能推荐

从零开始搭建Hadoop_创建一个hadoop项目-程序员宅基地

文章浏览阅读331次。第一部分:准备工作1 安装虚拟机2 安装centos73 安装JDK以上三步是准备工作,至此已经完成一台已安装JDK的主机第二部分:准备3台虚拟机以下所有工作最好都在root权限下操作1 克隆上面已经有一台虚拟机了,现在对master进行克隆,克隆出另外2台子机;1.1 进行克隆21.2 下一步1.3 下一步1.4 下一步1.5 根据子机需要,命名和安装路径1.6 ..._创建一个hadoop项目

心脏滴血漏洞HeartBleed CVE-2014-0160深入代码层面的分析_heartbleed代码分析-程序员宅基地

文章浏览阅读1.7k次。心脏滴血漏洞HeartBleed CVE-2014-0160 是由heartbeat功能引入的,本文从深入码层面的分析该漏洞产生的原因_heartbleed代码分析

java读取ofd文档内容_ofd电子文档内容分析工具(分析文档、签章和证书)-程序员宅基地

文章浏览阅读1.4k次。前言ofd是国家文档标准,其对标的文档格式是pdf。ofd文档是容器格式文件,ofd其实就是压缩包。将ofd文件后缀改为.zip,解压后可看到文件包含的内容。ofd文件分析工具下载:点我下载。ofd文件解压后,可以看到如下内容: 对于xml文件,可以用文本工具查看。但是对于印章文件(Seal.esl)、签名文件(SignedValue.dat)就无法查看其内容了。本人开发一款ofd内容查看器,..._signedvalue.dat

基于FPGA的数据采集系统(一)_基于fpga的信息采集-程序员宅基地

文章浏览阅读1.8w次,点赞29次,收藏313次。整体系统设计本设计主要是对ADC和DAC的使用,主要实现功能流程为:首先通过串口向FPGA发送控制信号,控制DAC芯片tlv5618进行DA装换,转换的数据存在ROM中,转换开始时读取ROM中数据进行读取转换。其次用按键控制adc128s052进行模数转换100次,模数转换数据存储到FIFO中,再从FIFO中读取数据通过串口输出显示在pc上。其整体系统框图如下:图1:FPGA数据采集系统框图从图中可以看出,该系统主要包括9个模块:串口接收模块、按键消抖模块、按键控制模块、ROM模块、D.._基于fpga的信息采集

微服务 spring cloud zuul com.netflix.zuul.exception.ZuulException GENERAL-程序员宅基地

文章浏览阅读2.5w次。1.背景错误信息:-- [http-nio-9904-exec-5] o.s.c.n.z.filters.post.SendErrorFilter : Error during filteringcom.netflix.zuul.exception.ZuulException: Forwarding error at org.springframework.cloud..._com.netflix.zuul.exception.zuulexception

邻接矩阵-建立图-程序员宅基地

文章浏览阅读358次。1.介绍图的相关概念  图是由顶点的有穷非空集和一个描述顶点之间关系-边(或者弧)的集合组成。通常,图中的数据元素被称为顶点,顶点间的关系用边表示,图通常用字母G表示,图的顶点通常用字母V表示,所以图可以定义为:  G=(V,E)其中,V(G)是图中顶点的有穷非空集合,E(G)是V(G)中顶点的边的有穷集合1.1 无向图:图中任意两个顶点构成的边是没有方向的1.2 有向图:图中..._给定一个邻接矩阵未必能够造出一个图

随便推点

MDT2012部署系列之11 WDS安装与配置-程序员宅基地

文章浏览阅读321次。(十二)、WDS服务器安装通过前面的测试我们会发现,每次安装的时候需要加域光盘映像,这是一个比较麻烦的事情,试想一个上万个的公司,你天天带着一个光盘与光驱去给别人装系统,这将是一个多么痛苦的事情啊,有什么方法可以解决这个问题了?答案是肯定的,下面我们就来简单说一下。WDS服务器,它是Windows自带的一个免费的基于系统本身角色的一个功能,它主要提供一种简单、安全的通过网络快速、远程将Window..._doc server2012上通过wds+mdt无人值守部署win11系统.doc

python--xlrd/xlwt/xlutils_xlutils模块可以读xlsx吗-程序员宅基地

文章浏览阅读219次。python–xlrd/xlwt/xlutilsxlrd只能读取,不能改,支持 xlsx和xls 格式xlwt只能改,不能读xlwt只能保存为.xls格式xlutils能将xlrd.Book转为xlwt.Workbook,从而得以在现有xls的基础上修改数据,并创建一个新的xls,实现修改xlrd打开文件import xlrdexcel=xlrd.open_workbook('E:/test.xlsx') 返回值为xlrd.book.Book对象,不能修改获取sheett_xlutils模块可以读xlsx吗

关于新版本selenium定位元素报错:‘WebDriver‘ object has no attribute ‘find_element_by_id‘等问题_unresolved attribute reference 'find_element_by_id-程序员宅基地

文章浏览阅读8.2w次,点赞267次,收藏656次。运行Selenium出现'WebDriver' object has no attribute 'find_element_by_id'或AttributeError: 'WebDriver' object has no attribute 'find_element_by_xpath'等定位元素代码错误,是因为selenium更新到了新的版本,以前的一些语法经过改动。..............._unresolved attribute reference 'find_element_by_id' for class 'webdriver

DOM对象转换成jQuery对象转换与子页面获取父页面DOM对象-程序员宅基地

文章浏览阅读198次。一:模态窗口//父页面JSwindow.showModalDialog(ifrmehref, window, 'dialogWidth:550px;dialogHeight:150px;help:no;resizable:no;status:no');//子页面获取父页面DOM对象//window.showModalDialog的DOM对象var v=parentWin..._jquery获取父window下的dom对象

什么是算法?-程序员宅基地

文章浏览阅读1.7w次,点赞15次,收藏129次。算法(algorithm)是解决一系列问题的清晰指令,也就是,能对一定规范的输入,在有限的时间内获得所要求的输出。 简单来说,算法就是解决一个问题的具体方法和步骤。算法是程序的灵 魂。二、算法的特征1.可行性 算法中执行的任何计算步骤都可以分解为基本可执行的操作步,即每个计算步都可以在有限时间里完成(也称之为有效性) 算法的每一步都要有确切的意义,不能有二义性。例如“增加x的值”,并没有说增加多少,计算机就无法执行明确的运算。 _算法

【网络安全】网络安全的标准和规范_网络安全标准规范-程序员宅基地

文章浏览阅读1.5k次,点赞18次,收藏26次。网络安全的标准和规范是网络安全领域的重要组成部分。它们为网络安全提供了技术依据,规定了网络安全的技术要求和操作方式,帮助我们构建安全的网络环境。下面,我们将详细介绍一些主要的网络安全标准和规范,以及它们在实际操作中的应用。_网络安全标准规范