日期格式化工具類

/日期格式化工具類***/

public class DateUtil {
    private static String pattern = "今天是yyyy-MM-dd E HH:mm:ss";
    private static SimpleDateFormat patternDF = new SimpleDateFormat(pattern, Locale.CHINA);
    private static final SimpleDateFormat MMdd = new SimpleDateFormat("MM/dd");
    public static final SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyy-MM-dd");
    private static final SimpleDateFormat yyyyMMddNoSep = new SimpleDateFormat("yyyyMMdd");
    private static final SimpleDateFormat HHmmss = new SimpleDateFormat("HH:mm:ss");
    private static final SimpleDateFormat yyyyMMddHHmmss = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");
    private static final SimpleDateFormat yyyyMMddHHmmss2 = new SimpleDateFormat(
    "yyyy-MM-dd HH:mm");
    private static final SimpleDateFormat yyyyMMddHHmmssNoSep = new SimpleDateFormat(
            "yyyyMMddHHmmss");
    private static final SimpleDateFormat yyyyMMddHHmmssSSS=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");

    private static final SimpleDateFormat yyyyMM = new SimpleDateFormat("yyyy-MM");
    private static final SimpleDateFormat yyyyMMNoSep = new SimpleDateFormat("yyyyMM");
    private static final SimpleDateFormat MS=new SimpleDateFormat("HH:mm:ss.S");

    public static String makeCurrentDateTimeStr() {
        return patternDF.format(getCurrentDate());
    }

    public static String formatDate(Date d) {
        if (d == null)
            return "";
        return yyyyMMdd.format(d);
    }

    public static Date formatStrDate(String d) {
        if (d == null)
            return getCurrentDate();

        Date date = null;
        try {
            date = yyyyMMdd.parse(d);
        } catch (ParseException e) {
            e.printStackTrace();
            return getCurrentDate();
        }
        return date;
    }

    public static Date formatYMD(String d){
         if (d == null)
             return getCurrentDate();

         Date date = null;
         try {
             date = yyyyMMddNoSep.parse(d);
         } catch (ParseException e) {
             e.printStackTrace();
             return getCurrentDate();
         }
         return date;

    }

    public static Date formatStrDateTime(String d) {
        if (StringUtil.isEmpty(d))
            return getCurrentDate();

        Date date = null;
        try {
            date = yyyyMMddHHmmss.parse(d);
        } catch (ParseException e) {
            e.printStackTrace();
            return getCurrentDate();
        }
        return date;
    }

    public static Date formatStrDateTime2(String d) {
        if ( StringUtil.isEmpty(d))
            return getCurrentDate();

        Date date = null;
        try {
            date = yyyyMMddHHmmss2.parse(d);
        } catch (ParseException e) {
            e.printStackTrace();
            return getCurrentDate();
        }
        return date;
    }

    public static String formatDate(String strDate) {
        if (strDate == null || strDate.trim().equals(""))
            return StringUtil.EMPTY;
        try {
            return yyyyMMdd.format(yyyyMMdd.parse(strDate));
        } catch (ParseException e) {
            e.printStackTrace();
            return StringUtil.EMPTY;
        }
    }

    public static String formatTime(Date d) {
        if (d == null)
            return StringUtil.EMPTY;
        return HHmmss.format(d);
    }

    public static String formatDateTimeStr(String strTime) {
        Date date=null;
        if (strTime == null || strTime.length() <= 0) {
            return "";
        }
        try {
            date = yyyyMMddHHmmss.parse(strTime);
            return yyyyMMddHHmmss.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String formatDateTime(Date d) {
        if (d == null)
            return StringUtil.EMPTY;
        return yyyyMMddHHmmss.format(d);
    }


    public static String formatDateTimeMS(Date d){
        if (d == null)
            return StringUtil.EMPTY;
        return yyyyMMddHHmmssSSS.format(d);
    }

    public static Date formatDateTime(String strTime){
        Date date=null;
        if(StringUtil.isEmpty(strTime))
            return date;

        try {
            date = yyyyMMddHHmmss.parse(strTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return date;
    }
    public static String formatDateTime2(Date d) {
        if (d == null)
            return StringUtil.EMPTY;
        return yyyyMMddHHmmss2.format(d);
    }
    public static String formatDateTimeNoSep(Date d) {
        if (d == null)
            return StringUtil.EMPTY;
        return yyyyMMddHHmmssNoSep.format(d);
    }

    public static String formatyyMM(Date d) {
        if (d == null) {
            return StringUtil.EMPTY;
        }
        return yyyyMM.format(d);
    }

    /**
     * yyyyMMddHHmmss--->yyyyMMdd
     * 
     * @param text
     * @return
     */
    public static String renderDate(String text) {
        if (StringUtil.isEmpty(text)) {
            return StringUtil.EMPTY;
        }
        int idx = text.indexOf(" ");
        if (idx <= 0) {
            return text;
        }
        return text.substring(0, idx).trim();
    }

    /**
     * yyyyMMddHHmmss--->yyyyMMdd
     * 
     * @param text
     * @return
     */
    public static String renderTime(String text) {
        if (StringUtil.isEmpty(text)) {
            return StringUtil.EMPTY;
        }
        int idx = text.indexOf(" ");
        if (idx <= 0) {
            return text;
        }
        return text.substring(idx).trim();
    }

    public static String formatNextMonthDate(String date) {
        String strDate = "";
        Date d = formatStrDate(date);
        Date currentDate = d;
        if (currentDate == null) {
            Date nextMonth = new Date(getCurrentDate().getTime() + (24 * 60 * 60 * 1000));
            strDate = formatDate(nextMonth);
        } else {
            Date nextMonth = new Date(currentDate.getTime() + (24 * 60 * 60 * 1000));
            strDate = formatDate(nextMonth);
        }
        return strDate;
    }

    public static String formatPrevMonthDate(Date date) {
        Calendar cal = Calendar.getInstance();
        if (date != null) {
            cal.setTimeInMillis(date.getTime());
        }
        cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1);
        String strTime = formatDate(new Date(cal.getTimeInMillis()));
        return strTime.replace("-", "").substring(0, 6);
    }

    public static String formatTime(int seconds) {
        String ret = "00:00:00";
        if (seconds <= 0)
            return ret;
        int sec = seconds % 60;
        int min = (seconds / 60) % 60;
        int hr = seconds / 3600;
        Calendar cal = Calendar.getInstance();
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH),
                hr, min, sec);
        ret = String.format("%1$tH:%1$tM:%1$tS", new Date(cal.getTimeInMillis()));
        return ret;
    }

    public static String formatYearMonth(Date date) {
        String str = "";
        if (date == null) {
            str = yyyyMMNoSep.format(getCurrentDate());
        } else {
            str = yyyyMMNoSep.format(date);
        }
        return str;
    }

    public static String formatYearMonth() {
        return formatYearMonth(null);
    }

    public static String formatYMD(Date date) {
        String str = "";
        if (date == null) {
            str = yyyyMMddNoSep.format(getCurrentDate());
        } else {
            str = yyyyMMddNoSep.format(date);
        }
        str = str.replaceAll("-", "");
        return str;
    }


    public static Date getCurrentDate() {
        return new Date(System.currentTimeMillis());
    }

    public static long getCurrentTimeMills() {
        return System.currentTimeMillis();
    }

    public static String formatMMDD(String date) {
        try {
            Date d = formatStrDate(date);
            return MMdd.format(new Date(d.getTime()));
        } catch (Exception e) {
            return MMdd.format(new Date());
        }
    }

    public static String[] getOneWeekDateLable() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, -7);
        String[] dateArr = new String[7];
        for (int i = 0; i < 7; i++) {
            dateArr[i] = DateUtil.formatDate(cal.getTime());
            cal.add(Calendar.DAY_OF_MONTH, 1);
        }
        return dateArr;
    }

    public static String[] getFormatOneWeekDateLable(String[] dates) {
        String[] dateArr = new String[dates.length];
        for (int i = 0; i < 7; i++) {
            dateArr[i] = DateUtil.formatMMDD(dates[i]);
        }
        return dateArr;
    }

    /**
     * 
     * Return a date string formatted by YYYY-MM-DD.
     * 
     * @param spanType
     *            The type you want to span, such as Calendar.MONTH
     * @param span
     *            The count you want to span
     * @return
     */
    public static String getDateStr(int spanType, int span) {
        Calendar cal = Calendar.getInstance();
        cal.add(spanType, span);
        return formatDate(new Date(cal.getTimeInMillis()));
    }

    /**
     * 
     * Judge if the given string is a valid date format
     * 
     * @param s
     * @return
     */
    public static boolean isValidDate(String s) {
        try {
            if (s.length() > 19) {
                return false;
            } else {
                yyyyMMddHHmmss.parse(s);
                return true;
            }
        } catch (Exception e) {
            // 如果throw java.text.ParseException或者NullPointerException,就說明格式不對
            return false;
        }
    }

    /**
     * 
     * Format the given string to date, if the time part is not "00:00:00",
     * return the date part.
     * 
     * @param str
     * @return
     */
    public static String getDate(String str) {
        String s;
        try {
            java.util.Date d = yyyyMMddHHmmss.parse(str);
            s = formatDateTime(d);
            if (s.indexOf("00:00:00") != -1) {
                return s.substring(0, s.indexOf("00:00:00")).trim();
            } else {
                return s;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String formatMS(Date date){
          if (date == null)
              return StringUtil.EMPTY;
          return MS.format(date);
    }

    public static String saveDate(String createDate){
        String dateCatalogue=DateUtil.formatDate((DateUtil.formatStrDateTime(createDate.replace("/", "-")))).replace("-", "_");

        return dateCatalogue;
    }

    public static String getFileDateTime(String dateTime){
        char[] strArray=dateTime.toCharArray();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<strArray.length;i++){
            sb.append(strArray[i]);
            if(i==3)
                sb.append("-");
            else if(i==5)
                sb.append("-");
            else if(i==7){
                sb.append(" ");
            }
            else if(i==9){
                sb.append(":");
            }else if(i==11)
                sb.append(":");

        }


        return sb.toString();
    }

    public static Date readDate(String catalogue) {
        Date date = formatStrDateTime(catalogue.replace("_", "-")
                + " 10:00:00");
        return date;

    }

    /**
     * 將時間轉換爲文件名稱
     * @param dateTime
     * @return
     */
    public static String convertTimeToFileName(String dateTime, String suffix){
        return dateTime.replace("-", "").replace(":", "").replace(" ", "") + suffix;
    }

    public static String formatDate(SimpleDateFormat format, Date date){
        if (date == null)
            return format.format(new Date());
        return format.format(date);
    }
}
發佈了32 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章