日期时间处理工具类_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

智能推荐

安装Keras,tensorflow,并将虚拟环境添加到jupyter notebook_scipy库怎么导入jupyter-程序员宅基地

文章浏览阅读4.5k次,点赞8次,收藏69次。安装Keras,tensorflow,并将虚拟环境添加到jupyter notebook_scipy库怎么导入jupyter

ARM开发软件ADS教程_arm.developer.suite使用教程-程序员宅基地

文章浏览阅读4.7k次。ARM开发软件ADS教程 ADS(ARM Developer Suite)是ARM公司推出ARM集成开发环境,操作简单方便,获得广大开发人员的青睐。下面使用ADS v1.2做一个实例教程,帮助大家学会使用ADS编写程序和仿真调试。(使用汇编语言) 首先:下载ADS v1.2版本(英文版)并安装好ADS。安装好ADS之后可以看到开始菜单---所有程序---ARM Developer Suit_arm.developer.suite使用教程

Python的datetime_python 手写datetime-程序员宅基地

文章浏览阅读4.6k次。Python提供了多个内置模块用于操作日期时间,像calendar,time,datetime。time模块我在之前的文章已经有所介绍,它提供的接口与C标准库time.h基本一致。相比于time模块,datetime模块的接口则更直观、更容易调用。今天就来讲讲datetime模块。 datetime模块定义了两个常量:datetime.MINYEAR和datetime.MAXYEAR,分_python 手写datetime

利用Excel数据爬虫_excel爬虫-程序员宅基地

文章浏览阅读2.4k次,点赞2次,收藏8次。URL部分和URL预览填写为目标(需要爬取数据的网址)的URL地址。第三部找到User-Agent的value复制。就可以在Excel表格里看到想要的数据了。1、在Excel里数据里打开自网站。命令超时选择1分钟即可。HTTP请求标头参数。_excel爬虫

Azure OpenAI:使用Completion/ChatCompletion实现更多可能合集(持续更新)_chatcompletion azure-程序员宅基地

文章浏览阅读198次。不过类似的提示词在GPT4模型下直接使用并不能产生类似的结果,GPT4使用的是ChatCompletion,可以在System Message里或者JSON格式的User Message里带更多的上下文信息过去,在这个案例里GPT4过于智能的将两个表进行了交叉查询,看到网上有其他开发人员使用了JSON解析的方法来拼出SQL文,有机会可以尝试。###创建SQL查询问题:Dear, 210430预计什么时间有货可发?###创建SQL查询问题:Dear, 210430预计什么时间有货可发?_chatcompletion azure

oracle 磁盘空间满后导致无法连接/登陆/使用/启动_oracle的链接数占满sqlplus无法登陆进去怎么处理的-程序员宅基地

文章浏览阅读8.3k次,点赞2次,收藏19次。某天登陆服务器后连接oracle数据库时,突然提示磁盘控件不足,导致sqlplus 登陆失败,提示如下图: 通过命令 df -lh /opt/oracle查看oracle安装目录所在磁盘空间,发现确实已使用100%,如下图: oracle安装目录所在磁盘整个大小才20G,为了一劳永逸,果断准备将oracle系统表空间的数据文件迁移到其他磁盘。此时处理思路应该是先关闭oracle服务,然..._oracle的链接数占满sqlplus无法登陆进去怎么处理的

随便推点

计算机毕业设计 SSM与Vue的勤工助学管理系统(源码+论文)_ssm+vue勤工助学-程序员宅基地

文章浏览阅读199次。Hi,各位同学好呀,这里是M学姐!今天向大家分享一个今年(2022)最新完成的毕业设计项目作品,【基于SSM的勤工助学管理系统】学姐根据实现的难度和等级对项目进行评分(最低0分,满分5分)难度系数:3分工作量:5分创新点:3分界面美化:5分界面美化的补充说明:使用vue的基本都能达到5分本项目完成于2022年6月份,包含内容 : 源码 + 论文 + 答辩PPT在开放的互联网平台面前,勤工助学管理系统的信息管理面临着巨大的挑战。传统的管理模式局限于简单数据的管理,无法适应不断变化的市场格局。_ssm+vue勤工助学

分布式锁原理与实现--Redis分布式锁和ZooKeeper分布式锁-程序员宅基地

文章浏览阅读334次,点赞5次,收藏5次。分布式锁的设计和实现是一个复杂但至关重要的课题,不同的实现方式各具优势,根据系统的实际需求和现有技术栈选择合适的分布式锁方案至关重要。在分布式系统中,由于数据分散存储在不同的节点上,当多个节点同时对同一资源进行操作时,如果没有有效的协调机制,就可能出现并发控制问题,导致数据的不一致和冲突。使用setnx命令尝试设置一个唯一的key-value对,key通常与待保护的资源相关联,value可以是线程ID或随机生成的UUID,如果设置成功,则认为获取到了锁。

联想服务器TD630安装系统,ThinkServer_TD340_RAID及系统安装.docx-程序员宅基地

文章浏览阅读597次。ThinkServer_TD340_RAID及系统安装Lenovo ThinkServer TD340 RAID及系统安装前言:Lenovo ThinkServer TD340随机配备导航盘,其RAID及系统安装有两种方式可选:导航盘方式和传统方式。导航盘方式较为简洁,且在系统安装完成后无需再进行驱动安装,其驱动已集成在导航盘上,如以此方式安装按导航盘引导进行即可,在此不做详细介绍;传统方式..._联想服务器td340u盘安装win2008

java字符串转成utf-8_将字符串的编码格式转换为utf-8-程序员宅基地

文章浏览阅读2.1w次,点赞2次,收藏5次。方式一:/*** 将字符串的编码格式转换为utf-8** @param str* @return Name = new* String(Name.getBytes("ISO-8859-1"), "utf-8");*/public static String toUTF8(String str) {if (isEmpty(str)) {return "";}try {if (str.equals(n..._字符串转utf-8

手把手教你使用YOLOV5训练自己的目标检测模型-口罩检测-视频教程_搭建yolo目标检测的环境. 使用yolo-air模块来做实验-程序员宅基地

文章浏览阅读10w+次,点赞691次,收藏4k次。手把手教你使用YOLOV5训练自己的目标检测模型大家好,这里是肆十二(dejahu),好几个月没有更新了,这两天看了一下关注量,突然多了1k多个朋友关注,想必都是大作业系列教程来的小伙伴。既然有这么多朋友关注这个大作业系列,并且也差不多到了毕设开题和大作业提交的时间了,那我直接就是一波更新。这期的内容相对于上期的果蔬分类和垃圾识别无论是在内容还是新意上我们都进行了船新的升级,我们这次要使用YOLOV5来训练一个口罩检测模型,比较契合当下的疫情,并且目标检测涉及到的知识点也比较多,这次的内容除了可以作为大家_搭建yolo目标检测的环境. 使用yolo-air模块来做实验

Linux命令大全(非常详细)从零基础入门到精通,看完这一篇就够了_linux系统基本操作命令-程序员宅基地

文章浏览阅读6k次,点赞10次,收藏81次。网络安全行业产业以来,随即新增加了几十个网络安全行业岗位︰网络安全专家、网络安全分析师、安全咨询师、网络安全工程师、安全架构师、安全运维工程师、渗透工程师、信息安全管理员、数据安全工程师、网络安全运营工程师、网络安全应急响应工程师、数据鉴定师、网络安全产品经理、网络安全服务工程师、网络安全培训师、网络安全审计员、威胁情报分析工程师、灾难恢复专业人员、实战攻防专业人员…最常用的打包命令是 tar,使用 tar 程序打出来的包我们常称为 tar 包,tar 包文件的命令通常都是以 .tar 结尾的。_linux系统基本操作命令

推荐文章

热门文章

相关标签