1. 程式人生 > >時間格式轉換公共類2

時間格式轉換公共類2

package DateUtil;

import java.util.Calendar;  
import java.util.Date;
import java.util.GregorianCalendar;
import java.text.FieldPosition;  
import java.text.ParsePosition;  
import java.text.SimpleDateFormat;  
 
/** 
 * 對日期的操作,如格式化,向前,向後推算日期 
 * SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
 * sdf.format(d)  
 *  
 */ 
public class DateUtil {  
      
    static final SimpleDateFormat sdf0 = new SimpleDateFormat("yyyy年MM月dd日");  
    static final SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");  
    static final SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
 
    /** 
     * 判斷指定日期、日期時間、時間是否比當前日期時間後。 
     *  
     * @param theTime 指定日期、日期時間、時間。 
     * @return 更後返回true,否則返回false。 
     */ 
    public static boolean isAfter(String theTime) {  
        switch (theTime.length()) {  
        case 5:  
            return (get("HH:mm").compareTo(theTime) > 0);  
        case 8:  
            return (get("HH:mm:ss").compareTo(theTime) > 0);  
        case 11:  
            if (theTime.charAt(2) == ' ')  
                return (get("dd HH:mm:ss").compareTo(theTime) > 0);  
            if (theTime.charAt(5) == ' ')  
                return (get("MM-dd HH:mm").compareTo(theTime) > 0);  
        case 14:  
            return (get("MM-dd HH:mm:ss").compareTo(theTime) > 0);  
        case 17:  
            return (get("yy-MM-dd HH:mm:ss").compareTo(theTime) > 0);  
        case 19:  
            return (get("yyyy-MM-dd HH:mm:ss").compareTo(theTime) > 0);  
        }  
        return false;  
    }  
      
    /** 
     * 判斷指定日期、日期時間、時間是否比當前日期時間前。 
     *  
     * @param theTime 指定日期、日期時間、時間。 
     * @return 更前返回true,否則返回false。 
     */ 
    public static boolean isBefore(String theTime) {  
        //補充程式碼
     
     switch (theTime.length()) {  
        case 5:
         
            return (get("HH:mm").compareTo(theTime) < 0);  
        case 8:  
            return (get("HH:mm:ss").compareTo(theTime) < 0);  
        case 11:  
            if (theTime.charAt(2) == ' ')  
                return (get("dd HH:mm:ss").compareTo(theTime) < 0);  
            if (theTime.charAt(5) == ' ')  
                return (get("MM-dd HH:mm").compareTo(theTime) < 0);  
        case 14:  
            return (get("MM-dd HH:mm:ss").compareTo(theTime) < 0);  
        case 17:  
            return (get("yy-MM-dd HH:mm:ss").compareTo(theTime) < 0);  
        case 19:
            return (get("yyyy-MM-dd HH:mm:ss").compareTo(theTime) < 0);
         
        }  
     
        return false;  
    }  
 
    /** 
     *  按照資料庫日期預定的格式取得當前的日期字串。 
     *  
     * * @return “yyyy-MM-dd”格式的當前時間字串。 
     */ 
    public static String getDate() {  
        return sdf2.format(new java.util.Date());  
    }  
      
    /** 
     * 獲取當時指定毫秒數後的日期物件。 
     *  
     * @param seconds 指定毫秒數。 
     * @return 當時指定毫秒數後的日期物件。 
     */ 
    public static java.util.Date getDate(long seconds) {  
        return new java.util.Date(new java.util.Date().getTime() + seconds* 1000);  
    }  
      
    /** 
     *  按照資料庫日期預定的格式取得當前的日期字串。 
     *  
     * * @return “yyyy-MM-dd”格式的當前時間字串。 
     */ 
    public static String getDate(Calendar ca) {  
        return sdf2.format(ca.getTime());  
    }  
 
    /** 
     *  按照資料庫日期預定的格式取得當前的日期字串。 
     *  
     * * @return “yyyy-MM-dd”格式的當前時間字串。 
     */ 
    public static String getDate(java.util.Date date) {  
        return sdf2.format(date);  
    }  
 
    /** 
     * 按照指定的日期/時間格式返回日期/時間字串。 
     *  
     * @param dateFormatString  格式字串。 
     * @return 格式化後的日期字串。 
     */ 
    public static String get(String dateFormatString) {  
        try {  
            return new java.text.SimpleDateFormat(dateFormatString)  
                    .format(new java.util.Date());  
        } catch (Exception e) {  
        }  
        return null;  
    }  
 
    /** 
     * 按照給定的 日期/時間 格式 生成 以java.util.Date物件給出的日期/時間 的字串。 
     *  
     * @param date 指定的日期物件。 
     * @param dateFormatString 格式字串。 
     * @return 格式化後的日期字串。 
     */ 
    public static String get(java.util.Date date, String dateFormatString) {  
       try {
        return new java.text.SimpleDateFormat(dateFormatString)  
           .format(date); 
 } catch (Exception e) {
  e.printStackTrace();
 }
        return null;  
    }  
 
    /** 
     * 按照給定的 日期/時間 格式 生成 以java.util.Calendar物件給出的日期/時間 的字串。 
     *  
     * @param calendar 指定的日曆物件。 
     * @param dateFormatString 格式字串。 
     * @return 格式化後的日期字串。 
     */ 
    public static String get(java.util.Calendar calendar, String dateFormatString) {  
        try {
          return new java.text.SimpleDateFormat(dateFormatString)  
             .format(calendar); 
  } catch (Exception e) {
  e.printStackTrace();
  }
        return null;  
    }  
 
    /** 
     * 自動分析多種格式的日期、日期時間、時間字串物件解析為Calendar物件,最小級別是秒級。 
     * 目前支援格式: 
     * yyyy-MM-dd HH:mm:ss 
     * MM-dd HH:mm:ss 預設為當年 
     * dd HH:mm:ss 預設為當年當月 
     * dd HH:mm 預設為當年當月 零秒 
     * MM-dd HH:mm 預設為當年 零秒 
     * yyyy-MM-dd 預設為零時零分零秒 
     * MM-dd 預設為當年 零時零分零秒 
     * HH:mm:ss 預設為當年當月當日 
     * HH:mm 預設為當年當月當日 零秒 
     *  
     * yyyy/MM/dd HH:mm:ss 
     * yy/MM/dd HH:mm:ss 
     * MM/dd HH:mm:ss 
     * dd HH:mm:ss 
     *  
     * yyyy年MM月dd日HH點mm分ss秒 
     * yy年MM月dd日HH點mm分ss秒 
     * MM月dd日HH點mm分ss秒 
     * dd日HH點mm分ss秒 
     * HH點mm分ss秒 
     * HH點mm分 
     * @param datetime 日期、日期時間、時間字串。 
     * @return 解析成功返回日曆物件,失敗返回null。 
     */ 
    public static Calendar parse(String datetime) {  
          
        if(datetime!=null){  
            //當不是標準格式時,則進行格式化  
            if (datetime.length()!=19) {  
                datetime=formatToEnglish(datetime);  
            }  
            try {  
                //建立一個日曆物件  
                Calendar rightNow = Calendar.getInstance();  
                  
                //設定日曆翻到指定日期時間  
                rightNow.setTime(sdf1.parse(datetime));  
                  
                //返回設定好的日期  
                return rightNow;  
              
            } catch (Exception e) { }  
        }  
          
        return null;  
          
    }  
      
    /** 
     * 用指定的日期物件得到日期時間的字串形式。 
     *  
     * @param date java.util.Date物件。 
     * @return 日期時間的字串形式。 
     */ 
    public static String getDateTime(java.util.Date date) {  
        return sdf1.format(date);  
    }  
      
    /** 
     * 用給定的日期得到指定延遲秒數的日期時間字串。 
     *  
     * @param date java.util.Date物件。 
     * @param seconds 秒數。 
     * @return 延遲後的日期時間。 
     */ 
    public static String getDateTime(java.util.Date date, int seconds) {  
        return sdf1.format(new java.util.Date(date.getTime() + seconds * 1000));  
    }  
      
    /** 
     * 獲得今日與指定日曆之間的天數。 
     *  
     * @param last 指定的日曆。 
     * @return 當日與指定日曆之間的天數。 
     */ 
    public static int getDays(Calendar last) {  
        Calendar right = Calendar.getInstance();  
          
        long theTime = right.getTimeInMillis() - last.getTimeInMillis();  
          
        return (int) (theTime / (3600000 * 24));  
    }  
 
    private static int seed = 0;  
 
    /** 
     * 獲取毫秒級的指定長度的字串。 
     * @param length 指定的字串長度。 
     * @return 毫秒級的指定長度的字串。 
     */ 
    public static String getRandomString(int length) {  
        seed++;  
          
        Calendar right = Calendar.getInstance();  
        String tmp = Long.toString(right.getTimeInMillis() * seed + seed);  
          
        length = tmp.length() - length;  
          
        return (length < 0) ? tmp : tmp.substring(length);  
    }  
 
    /** 
     * 用指定格式的日期時間來的得到日期時間物件。 
     *  
     * @param dateFormatString 日期時間格式字串。 
     * @return 返回java.util.Date型別日期時間物件。 
     */ 
    public static java.util.Date getToday(String dateFormatString) {  
        try {  
            return parse(  
                    new java.text.SimpleDateFormat(dateFormatString)  
                            .format(Calendar.getInstance().getTime()))  
                    .getTime();  
        } catch (Exception e) {  
        }  
 
        return null;  
    }  
 
    /** 
     * 得到指定格式的當日的後一天的日期時間物件。 
     *  
     * @param dateFormatString 日期時間格式字串。 
     * @return 返回java.util.Date型別日期時間物件。 
     */ 
    public static java.util.Date getTomorrow(String dateFormatString) {  
        try {  
            return parse(  
                    new java.text.SimpleDateFormat(dateFormatString)  
                            .format(new java.util.Date(new java.util.Date()  
                                    .getTime() + 24 * 3600 * 1000))).getTime();  
        } catch (Exception e) {  
        }  
 
        return null;  
    }  
      
    /** 
     * 返回今天之前或之後若干天的日期字串。 
     * @param days 指定的天數,“days<0”表示前days天;“days>0”表示後days天,“days=0”表示當天。 
     * @return 返回格式為“yyyy-MM-dd”的日期。 
     */ 
    public static String getDate(int days) {  
        Calendar now = Calendar.getInstance();  
        now.add(Calendar.DAY_OF_MONTH, days);  
        return sdf2.format(now.getTime());  
    }  
 
    /** 
     * 得到指定date日期之前或之後若干天的日期字串。 
     * @param date 指定的日期字串。 
     * @param days 指定的天數,“days<0”表示前days天;“days>0”表示後days天,“days=0”表示當天。 
     * @return 字串形式的日期。 
     */ 
    public static String getDate(String date,int days){  
        java.util.Date dateTemp = sdf2.parse(date, new ParsePosition(0));  
          
        Calendar calendar = Calendar.getInstance();  
        calendar.setTime(dateTemp);  
          
        // 要加減的日期  
        calendar.add(Calendar.DATE, days);  
 
        java.util.Date nowTime = calendar.getTime();  
 
        StringBuffer buffer = sdf2.format(nowTime, new StringBuffer(""),new FieldPosition(0));  
 
        return new String(buffer);  
    }  
      
    /** 
     * 格式化以:“年”、“月”、“日”、“時”、“分”、“秒”、“-”、“-”、“:”、“/”、“ ”、“ ” 
     * 分割日期時間的日期時間字串。統一格式化成英文的日期時間,例:2009-11-09 13:32:56。 
     */ 
    public static String formatToEnglish(String datetime){  
        String date=sdf2.format(Calendar.getInstance().getTime());  
          
        String yy=date.substring(0,2);  
        String year=date.substring(0,4);  
        String month=date.substring(5,7);  
        String day=date.substring(8,10);  
          
        String datetimeBak=datetime.replace("日", " ");  
        datetimeBak=datetimeBak.replace(" ", " ");        
        datetimeBak=datetimeBak.replaceAll(" +", " ");  
          
        //把日期和時間切割成兩部分  
        String dt[]=datetimeBak.split(" ");  
          
        String format=null;  
          
        String temp[]=getArray(datetime);  
        if(temp!=null&&dt!=null){  
              
            switch (temp.length){  
            case 1:  
                //只有日  
                if(temp[0].length()==1){  
                    temp[0]="0"+temp[0];  
                }  
                format=year+"-"+month+"-"+temp[1]+" 00:00:00";    
                break;  
            case 2:  
                for (int i = 0; i < temp.length; i++) {  
                    if(temp[i].length()==1){  
                        temp[i]="0"+temp[i];  
                    }  
                }  
                  
                //判斷為日期或是時間  
                if(dt.length==1){  
                    //判斷為時間:由時、分、秒組成  
                    if(dt[0].contains(":")||dt[0].contains(":")||dt[0].contains("點")){  
                        format=year+"-"+month+"-"+day+" "+temp[0]+":"+temp[1]+":00";  
                    }  
                    //判斷為日期:由月、日組成  
                    else{  
                        format=year+"-"+temp[0]+"-"+temp[1]+" 00:00:00";  
                    }  
                }  
                //判斷為日期時間:由日、時組成  
                else if(dt.length==2){  
                    format=year+"-"+month+"-"+temp[0]+" "+temp[1]+":00:00";  
                }  
                  
                break;  
            case 3:  
                //判斷為日期或是時間  
                if(dt.length==1){  
                    //判斷為時間:由時、分、秒組成  
                    if(dt[0].contains(":")||dt[0].contains(":")||dt[0].contains("點")){  
                        for (int i = 0; i < temp.length; i++) {  
                            if(temp[i].length()==1){  
                                temp[i]="0"+temp[i];  
                            }  
                        }  
                        format=year+"-"+month+"-"+day+" "+temp[0]+":"+temp[1]+":"+temp[2];  
                    }  
                    //判斷為日期:由年、月、日組成  
                    else{  
                        for (int i = 0; i < temp.length; i++) {  
                            if(temp[0].length()!=4){  
                                temp[0]=yy+temp[0];  
                            }  
                            else if(temp[i].length()==1){  
                                temp[i]="0"+temp[i];  
                            }  
                        }  
                        format=temp[0]+"-"+temp[1]+"-"+temp[2]+" 00:00:00";  
                    }  
                }  
                //判斷為日期時間:由日、時組成  
                else if(dt.length==2){  
                    for (int i = 0; i < temp.length; i++) {  
                        if(temp[i].length()==1){  
                            temp[i]="0"+temp[i];  
                        }  
                    }  
                      
                    String dateArray[]=getArray(dt[0]);  
                    String timeArray[]=getArray(dt[1]);  
                    //判斷為月、日、時組成  
                    if(dateArray.length==2 && timeArray.length==1){  
                        format=year+"-"+temp[0]+"-"+temp[1]+" "+temp[2]+":00:00";  
                    }  
                    //判斷為日、時、分組成  
                    else if(dateArray.length==1 && timeArray.length==2){  
                        format=year+"-"+month+"-"+temp[0]+" "+temp[1]+":"+temp[2]+":00";  
                    }  
                }  
                break;  
            case 4:  
                //判斷為日期時間  
                if(dt.length==2){  
                      
                    String dateArray[]=getArray(dt[0]);  
                    String timeArray[]=getArray(dt[1]);  
                      
                    //判斷為年、月、日、時組成  
                    if(dateArray.length==3 && timeArray.length==1){  
                        for (int i = 0; i < temp.length; i++) {  
                            if(temp[0].length()!=4){  
                                temp[0]=yy+temp[0];  
                            }  
                            else if(temp[i].length()==1){  
                                temp[i]="0"+temp[i];  
                            }  
                        }  
                        format=temp[0]+"-"+temp[1]+"-"+temp[2]+" "+temp[3]+":"+"00:00";  
                    }  
                    else{  
                        for (int i = 0; i < temp.length; i++) {  
                            if(temp[i].length()==1){  
                                temp[i]="0"+temp[i];  
                            }  
                        }  
                          
                        //判斷為日、時、分、秒組成  
                        if(dateArray.length==1 && timeArray.length==3){  
                            format=year+"-"+month+"-"+temp[0]+" "+temp[1]+":"+temp[2]+":"+temp[3];  
                        }  
                        //判斷為月、日、時、分組成  
                        else if(dateArray.length==2 && timeArray.length==2){  
                            format=year+"-"+temp[0]+"-"+temp[1]+" "+temp[2]+":"+temp[3]+":00";  
                        }  
                    }  
                }  
                  
                break;  
            case 5:  
                if(dt.length==2){  
                    String dateArray[]=getArray(dt[0]);  
                    String timeArray[]=getArray(dt[1]);  
                    //判斷為月、日、時、分、秒組成  
                    if(dateArray.length==2 && timeArray.length==3){  
                        for (int i = 0; i < temp.length; i++) {  
                            if(temp[i].length()==1){  
                                temp[i]="0"+temp[i];  
                            }  
                        }  
                        format=year+"-"+temp[0]+"-"+temp[1]+" "+temp[2]+":"+temp[3]+":"+temp[4];  
                    }  
                    //判斷為年、月、日、時、分組成  
                    else if(dateArray.length==3 && timeArray.length==2){  
                        for (int i = 0; i < temp.length; i++) {  
                            if(temp[0].length()!=4){  
                                temp[0]=yy+temp[0];  
                            }  
                            else if(temp[i].length()==1){  
                                temp[i]="0"+temp[i];  
                            }  
                        }  
                        format=temp[0]+"-"+temp[1]+"-"+temp[2]+" "+temp[3]+":"+temp[4]+":00";  
                    }  
                }  
                break;  
            case 6:  
                for (int i = 0; i < temp.length; i++) {  
                    if(temp[0].length()!=4){  
                        temp[0]=yy+temp[0];  
                    }  
                    else if(temp[i].length()==1){  
                        temp[i]="0"+temp[i];  
                    }  
                }  
                format=temp[0]+"-"+temp[1]+"-"+temp[2]+" "+temp[3]+":"+temp[4]+":"+temp[5];   
                break;  
            }  
        }  
          
        return format;  
    }  
      
    /** 
     * 把多種中文中易出現格式的日期時間中各項轉換成陣列。 
     */ 
    private static String[] getArray(String datetime){  
        String array[]=null;  
        if(datetime!=null){  
              
            //把半形空格替換掉  
            datetime=datetime.replace(" ", "-");  
              
            //把全形空格替換掉  
            datetime=datetime.replace(" ", "-");  
            datetime=datetime.replace("年", "-");  
            datetime=datetime.replace("月", "-");  
            datetime=datetime.replace("日", "-");  
            datetime=datetime.replace("點", "-");  
            datetime=datetime.replace("分", "-");  
            datetime=datetime.replace("秒", "");  
            datetime=datetime.replace(",", "-");  
            datetime=datetime.replace(",", "-");  
            datetime=datetime.replace(".", "-");  
            datetime=datetime.replace(":", "-");  
            datetime=datetime.replace(":", "-");  
            datetime=datetime.replace("-", "-");  
            datetime=datetime.replace("/", "-");  
            //多個“-”替換成一個“-”  
            datetime=datetime.replaceAll("-+", "-");  
              
            //把日期時間分割成每個項  
            array=datetime.split("-");  
        }  
          
        return array;  
    }  
      
    /** 
     * 格式化以:“年”、“月”、“日”、“時”、“分”、“秒”、“-”、“-”、“:”、“/”、“ ”、“ ” 
     * 分割日期時間的日期時間字串。統一格式化成中文的日期時間,例:2009年11月09日13時32分56秒。 
     */ 
    public static String formatToChinese(String datetime){  
        datetime=formatToEnglish(datetime);  
        if(datetime==null||datetime.equals("")){  
            return null;  
        }  
          
        String str[]=datetime.split(":|-| ");  
          
        return str[0]+"年"+str[1]+"月"+str[2]+"日 "+str[3]+"點"+str[4]+"分"+str[5]+"秒";  
    }
   
   
    public static void main(String[] args) {
     Calendar c  = Calendar.getInstance();
  c.set(2011, 4, 1,8,30,50);
  Date dt = c.getTime();
  String formatDate  = sdf1.format(dt);
   DateUtil du = new DateUtil();

   //判斷指定日期、日期時間、時間是否比當前日期時間後
     System.out.println(du.isAfter(formatDate));
   
   //判斷指定日期、日期時間、時間是否比當前日期時間前
        System.out.println(du.isBefore(formatDate));
     
        //按照資料庫日期預定的格式取得當前的日期字串。
        System.out.println(du.getDate());
   //返回今天之前或之後若干天的日期字串
        System.out.println(du.getDate(100));
   //按照資料庫日期預定的格式取得當前的日期字串
        System.out.println(du.getDate(c));
        //獲得今日與指定日曆之間的天數
        System.out.println(du.getDays(c));
   //用指定格式的日期時間來的得到日期時間物件。 
        System.out.println(du.getToday(formatDate));
   //得到指定格式的當日的後一天的日期時間物件
       System.out.println(du.getTomorrow(formatDate));
   // 分割日期時間的日期時間字串。統一格式化成英文的日期時間,例:2009-11-09 13:32:56。
      System.out.println(du.formatToEnglish(formatDate));
   //
   System.out.print("現在離");
        System.out.print(du.formatToChinese(formatDate));
        System.out.print("還有" + du.getDays(c) + "天");
   
   
        
   
     
 }
   
}