首页 > 代码库 > DateUtils

DateUtils

  1 package com.gootrip.util;  2   3 /**  4  * <p>Title: 时间和日期的工具类</p>  5  * <p>Description: DateUtil类包含了标准的时间和日期格式,以及这些格式在字符串及日期之间转换的方法</p>  6  * <p>Copyright: Copyright (c) 2007 advance,Inc. All Rights Reserved</p>  7  * <p>Company: advance,Inc.</p>  8  * @author advance  9  * @version 1.0 10  */ 11 import java.text.DateFormat; 12 import java.text.ParseException; 13 import java.text.SimpleDateFormat; 14 import java.util.Calendar; 15 import java.util.Date; 16 import java.util.GregorianCalendar; 17  18 public class DateUtil { 19     //~ Static fields/initializers ============================================= 20  21     private static String datePattern = "MM/dd/yyyy"; 22  23     private static String timePattern = datePattern + " HH:MM a"; 24  25     //~ Methods ================================================================ 26  27     /** 28      * Return default datePattern (MM/dd/yyyy) 29      * @return a string representing the date pattern on the UI 30      */ 31     public static String getDatePattern() { 32         return datePattern; 33     } 34  35     /** 36      * This method attempts to convert an Oracle-formatted date 37      * in the form dd-MMM-yyyy to mm/dd/yyyy. 38      * 39      * @param aDate date from database as a string 40      * @return formatted string for the ui 41      */ 42     public static final String getDate(Date aDate) { 43         SimpleDateFormat df = null; 44         String returnValuehttp://www.mamicode.com/= ""; 45  46         if (aDate != null) { 47             df = new SimpleDateFormat(datePattern); 48             returnValue =http://www.mamicode.com/ df.format(aDate); 49         } 50  51         return (returnValue); 52     } 53  54     public static final String date2Str(Date aDate) { 55         SimpleDateFormat df = null; 56         String returnValuehttp://www.mamicode.com/= ""; 57  58         if (aDate != null) { 59             df = new SimpleDateFormat(datePattern); 60             returnValue =http://www.mamicode.com/ df.format(aDate); 61         } 62  63         return (returnValue); 64     } 65  66     public static final String date2Str(String pattern, Date aDate) { 67         SimpleDateFormat df = null; 68         String returnValuehttp://www.mamicode.com/= ""; 69  70         if (aDate != null) { 71             df = new SimpleDateFormat(pattern); 72             returnValue =http://www.mamicode.com/ df.format(aDate); 73         } 74         return (returnValue); 75     } 76  77     /** 78      * This method generates a string representation of a date/time 79      * in the format you specify on input 80      * 81      * @param aMask the date pattern the string is in 82      * @param strDate a string representation of a date 83      * @return a converted Date object 84      * @see java.text.SimpleDateFormat 85      * @throws ParseException 86      */ 87     public static final Date convertStringToDate(String aMask, String strDate) 88             throws ParseException { 89         SimpleDateFormat df = null; 90         Date date = null; 91         df = new SimpleDateFormat(aMask); 92  93         try { 94             date = df.parse(strDate); 95         } catch (ParseException pe) { 96             return null; 97         } 98  99         return (date);100     }101 102     public static final Date str2Date(String aMask, String strDate)103             throws ParseException {104         SimpleDateFormat df = null;105         Date date = null;106         df = new SimpleDateFormat(aMask);107 108         try {109             date = df.parse(strDate);110         } catch (ParseException pe) {111             return null;112         }113 114         return (date);115     }116 117     /**118      * This method returns the current date time in the format:119      * MM/dd/yyyy HH:MM a120      *121      * @param theTime the current time122      * @return the current date/time123      */124     public static String getTimeNow(Date theTime) {125         return getDateTime(timePattern, theTime);126     }127 128     /**129      * This method returns the current date in the format: MM/dd/yyyy130      *131      * @return the current date132      * @throws ParseException133      */134     public static Calendar getToday() throws ParseException {135         Date today = new Date();136         SimpleDateFormat df = new SimpleDateFormat(datePattern);137 138         // This seems like quite a hack (date -> string -> date),139         // but it works ;-)140         String todayAsString = df.format(today);141         Calendar cal = new GregorianCalendar();142         cal.setTime(convertStringToDate(todayAsString));143 144         return cal;145     }146 147     /**148      * This method generates a string representation of a date‘s date/time149      * in the format you specify on input150      *151      * @param aMask the date pattern the string is in152      * @param aDate a date object153      * @return a formatted string representation of the date154      *155      * @see java.text.SimpleDateFormat156      */157     public static final String getDateTime(String aMask, Date aDate) {158         SimpleDateFormat df = null;159         String returnValuehttp://www.mamicode.com/= "";160 161         if (aDate == null) {162             System.out.print("aDate is null!");163         } else {164             df = new SimpleDateFormat(aMask);165             returnValue =http://www.mamicode.com/ df.format(aDate);166         }167 168         return (returnValue);169     }170 171     /**172      * This method generates a string representation of a date based173      * on the System Property ‘dateFormat‘174      * in the format you specify on input175      *176      * @param aDate A date to convert177      * @return a string representation of the date178      */179     public static final String convertDateToString(Date aDate) {180         return getDateTime(datePattern, aDate);181     }182 183     /**184      * This method converts a String to a date using the datePattern185      *186      * @param strDate the date to convert (in format MM/dd/yyyy)187      * @return a date object188      *189      * @throws ParseException190      */191     public static Date convertStringToDate(String strDate)192             throws ParseException {193         Date aDate = null;194 195         try {196 197             aDate = convertStringToDate(datePattern, strDate);198         } catch (ParseException pe) {199             //log.error("Could not convert ‘" + strDate200             //          + "‘ to a date, throwing exception");201             pe.printStackTrace();202             return null;203 204         }205         return aDate;206     }207 208     //日期格式转换成时间戳209     public static long getTimeStamp(String pattern, String strDate) {210         long returnTimeStamp = 0;211         Date aDate = null;212         try {213             aDate = convertStringToDate(pattern, strDate);214         } catch (ParseException pe) {215             aDate = null;216         }217         if (aDate == null) {218             returnTimeStamp = 0;219         } else {220             returnTimeStamp = aDate.getTime();221         }222         return returnTimeStamp;223     }224 225     //获取当前日期的邮戳226     public static long getNowTimeStamp() {227         long returnTimeStamp = 0;228         Date aDate = null;229         try {230             aDate = convertStringToDate("yyyy-MM-dd HH:mm:ss", getNowDateTime());231         } catch (ParseException pe) {232             aDate = null;233         }234         if (aDate == null) {235             returnTimeStamp = 0;236         } else {237             returnTimeStamp = aDate.getTime();238         }239         return returnTimeStamp;240     }241 242     /**243      *得到格式化后的系统当前日期244      *@param strScheme 格式模式字符串245      *@return 格式化后的系统当前时间,如果有异常产生,返回空串""246      *@see java.util.SimpleDateFormat247      */248     public static final String getNowDateTime(String strScheme) {249         String strReturn = null;250         Date now = new Date();251         try {252             SimpleDateFormat sdf = new SimpleDateFormat(strScheme);253             strReturn = sdf.format(now);254         } catch (Exception e) {255             strReturn = "";256         }257         return strReturn;258     }259 260     public static final String getNowDateTime() {261         String strReturn = null;262         Date now = new Date();263         try {264             SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");265             strReturn = sdf.format(now);266         } catch (Exception e) {267             strReturn = "";268         }269         return strReturn;270     }271 272     /**273      *转化日期格式"MM/dd/YY、MM.dd.YY、MM-dd-YY、MM/dd/YY",并输出为正常的格式yyyy-MM-dd274      *@param strDate 待转换的日期格式275      *@return 格式化后的日期,如果有异常产生,返回空串""276      *@see java.util.SimpleDateFormat277      */278     public static final String convertNormalDate(String strDate) {279         String strReturn = null;280         //先把传入参数分格符转换成java认识的分格符281         String[] date_arr = strDate.split("\\.|\\/|\\-");282         try {283             if (date_arr.length == 3) {284                 if (date_arr[2].length() != 4) {285                     String nowYear = getNowDateTime("yyyy");286                     date_arr[2] = nowYear.substring(0, 2) + date_arr[2];287                 }288                 strReturn = DateUtil.getDateTime("yyyy-MM-dd",289                         convertStringToDate(combineStringArray(date_arr, "/")));290             }291 292         } catch (Exception e) {293             return strReturn;294         }295         return strReturn;296     }297 298     /**299      * 将字符串数组使用指定的分隔符合并成一个字符串。300      * @param array 字符串数组301      * @param delim 分隔符,为null的时候使用""作为分隔符(即没有分隔符)302      * @return 合并后的字符串303      * @since  0.4304      */305     public static final String combineStringArray(String[] array, String delim) {306         int length = array.length - 1;307         if (delim == null) {308             delim = "";309         }310         StringBuffer result = new StringBuffer(length * 8);311         for (int i = 0; i < length; i++) {312             result.append(array[i]);313             result.append(delim);314         }315         result.append(array[length]);316         return result.toString();317     }318 319     public static final int getWeekNum(String strWeek) {320         int returnValue = http://www.mamicode.com/0;321         if (strWeek.equals("Mon")) {322             returnValue = http://www.mamicode.com/1;323         } else if (strWeek.equals("Tue")) {324             returnValue = http://www.mamicode.com/2;325         } else if (strWeek.equals("Wed")) {326             returnValue = http://www.mamicode.com/3;327         } else if (strWeek.equals("Thu")) {328             returnValue = http://www.mamicode.com/4;329         } else if (strWeek.equals("Fri")) {330             returnValue = http://www.mamicode.com/5;331         } else if (strWeek.equals("Sat")) {332             returnValue = http://www.mamicode.com/6;333         } else if (strWeek.equals("Sun")) {334             returnValue = http://www.mamicode.com/0;335         } else if (strWeek == null) {336             returnValue = http://www.mamicode.com/0;337         }338 339         return returnValue;340     }341     /**342      * 获取日期字符串中的中文时间表示字符串343      * @param strDate344      * @return345      */346     public static final String getSabreTime(String strDate) {347         String strReturn = "";348         try {349 350             Date d = DateUtil.str2Date("yyyy-MM-dd HH:mm:ss", CTool.replace(351                     strDate, "T", " "));352             strReturn = DateUtil.date2Str("hh:mm aaa", d);353 354         } catch (Exception e) {355             return strReturn;356         }357         return strReturn;358     }359     /**360      * 获取日期字符串中的中文日期表示字符串361      * @param strDate362      * @return363      */364     public static final String getSabreDate(String strDate) {365         String strReturn = "";366         try {367             String p = null;368             if (strDate.length() > 10)369                 p = "yyyy-MM-dd HH:mm:ss";370             else371                 p = "yyyy-MM-dd";372             Date d = DateUtil.str2Date(p, CTool.replace(strDate, "T", " "));373             strReturn = DateUtil.date2Str("EEE d-MMM", d);374 375         } catch (Exception e) {376             return strReturn;377         }378         return strReturn;379     }380     /**381      * 获取日期字符串的中文日期时间表示382      * @param strDate383      * @return384      */385     public static final String getSabreDateTime(String strDate) {386         String strReturn = "";387         try {388             String p = null;389             if (strDate.length() > 10)390                 p = "yyyy-MM-dd HH:mm:ss";391             else392                 p = "yyyy-MM-dd";393             Date d = DateUtil.str2Date(p, CTool.replace(strDate, "T", " "));394             strReturn = DateUtil.date2Str("EEE d-MMM hh:mm aaa", d);395 396         } catch (Exception e) {397             return strReturn;398         }399         return strReturn;400     }401 402     /**403      *得到格式化后的指定日期404      *@param strScheme 格式模式字符串405      *@param date 指定的日期值406      *@return 格式化后的指定日期,如果有异常产生,返回空串""407      *@see java.util.SimpleDateFormat408      */409     public static final String getDateTime(Date date, String strScheme) {410         String strReturn = null;411         try {412             SimpleDateFormat sdf = new SimpleDateFormat(strScheme);413             strReturn = sdf.format(date);414         } catch (Exception e) {415             strReturn = "";416         }417 418         return strReturn;419     }420     /**421      * 获取日期422      * @param timeType 时间类型,譬如:Calendar.DAY_OF_YEAR423      * @param timenum  时间数字,譬如:-1 昨天,0 今天,1 明天424      * @return 日期425      */426     public static final Date getDateFromNow(int timeType, int timenum){427         Calendar cld = Calendar.getInstance();428         cld.set(timeType, cld.get(timeType) + timenum);429         return cld.getTime();430     }431     /**432      * 获取日期433      * @param timeType 时间类型,譬如:Calendar.DAY_OF_YEAR434      * @param timenum  时间数字,譬如:-1 昨天,0 今天,1 明天435      * @param format_string 时间格式,譬如:"yyyy-MM-dd HH:mm:ss"436      * @return 字符串437      */438     public static final String getDateFromNow(int timeType, int timenum, String format_string){439         if ((format_string == null)||(format_string.equals("")))440             format_string = "yyyy-MM-dd HH:mm:ss";441         Calendar cld = Calendar.getInstance();442         Date date = null;443         DateFormat df = new SimpleDateFormat(format_string);444         cld.set(timeType, cld.get(timeType) + timenum);445         date = cld.getTime();446         return df.format(date);447     }448     /**449      * 获取当前日期的字符串450      * @param format_string 时间格式,譬如:"yyyy-MM-dd HH:mm:ss"451      * @return 字符串452      */453     public static final String getDateNow(String format_string){454         if ((format_string == null)||(format_string.equals("")))455             format_string = "yyyy-MM-dd HH:mm:ss";456         Calendar cld = Calendar.getInstance();457         DateFormat df = new SimpleDateFormat(format_string);458         return df.format(cld.getTime());459     }460 461 }

 

DateUtils