zoukankan      html  css  js  c++  java
  • Java中的操作日期的工具类

      1 import java.text.DateFormat;
      2 import java.text.ParseException;
      3 import java.text.SimpleDateFormat;
      4 import java.util.Calendar;
      5 import java.util.Date;
      6 import java.util.GregorianCalendar;
      7 import java.util.Locale;
      8 import java.util.MissingResourceException;
      9 import java.util.ResourceBundle;
     10 
     11 import javax.xml.datatype.DatatypeConfigurationException;
     12 import javax.xml.datatype.DatatypeFactory;
     13 import javax.xml.datatype.XMLGregorianCalendar;
     14 
     15 /**
     16  * Date Utility Class This is used to convert Strings to Dates and Timestamps
     17  * 格式约定
     18  * 字母  日期或时间元素 表示  示例  
     19  * G  Era 标志符  Text  AD  
     20  * y  年  Year  1996; 96 
     21  * M  年中的月份  Month  July; Jul; 07 
     22  * w  年中的周数  Number  27 
     23  * W  月份中的周数  Number  2 
     24  * D  年中的天数  Number  189 
     25  * d  月份中的天数  Number  10 
     26  * F  月份中的星期  Number  2 
     27  * a  Am/pm 标记  Text  PM  
     28  * H  一天中的小时数(0-23)  Number  0 
     29  * k  一天中的小时数(1-24)  Number  24 
     30  * K  am/pm 中的小时数(0-11)  Number  0 
     31  * h  am/pm 中的小时数(1-12)  Number  12 
     32  * m  小时中的分钟数  Number  30 
     33  * s  分钟中的秒数  Number  55 
     34  * S  毫秒数  Number  978 
     35  * z  时区  General time zone  Pacific Standard Time; PST; GMT-08:00 
     36  * Z  时区  RFC 822 time zone  -0800 
     37 
     38  * StandardDate : [String][yyyy-MM-dd] 2015-01-05
     39  * StandardTime : [String][HH:mm:ss]   20:39:26
     40  * Standard     : [String][yyyy-MM-dd HH:mm:ss] 2015-01-05 20:39:26
     41  * <p>
     42  * <a href="DateUtil.java.html"><i>View Source</i></a>
     43  * </p>
     44  * 
     45  * @author <a href="mailto:xia_chaojun@newautovideo.com">chaojun xia</a> Minutes
     46  *         should be mm not MM (MM is month).
     47  * @version $Revision: 1.0.0.1 $ $Date: 2006/08/30 13:59:59 $
     48  */
     49 public class DateUtil {
     50 
     51     private static String defaultDatePattern = null;
     52 
     53     private static String timePattern = "HH:mm";
     54 
     55     /**
     56      * Return default datePattern (MM/dd/yyyy)
     57      * 
     58      * @return a string representing the date pattern on the UI
     59      */
     60     public static synchronized String getDatePattern() {
     61         Locale locale = LocaleContextHolder.getLocale();
     62         try {
     63             /* extract default date pattern from application context */
     64             defaultDatePattern = ResourceBundle.getBundle("ApplicationResources", locale).getString("date.format");
     65         } catch (MissingResourceException mse) {
     66             defaultDatePattern = "MM/dd/yyyy";
     67         }
     68 
     69         return defaultDatePattern;
     70     }
     71 
     72     /**
     73      * Return default datetimePattern (MM/dd/yyyy HH:mm:ss.S)
     74      * 
     75      * @return a string representing the datetime pattern on the UI
     76      */
     77     public static String getDateTimePattern() {
     78         return DateUtil.getDatePattern() + " HH:mm:ss.S";
     79     }
     80 
     81     /**
     82      * This method attempts to convert an Oracle-formatted date in the form
     83      * dd-MMM-yyyy to mm/dd/yyyy.
     84      * 
     85      * @param aDate
     86      *            date from database as a string
     87      * @return formatted string for the ui
     88      */
     89     public static final String getDate(Date aDate) {
     90         SimpleDateFormat df = null;
     91         String returnValue = "";
     92         if (aDate != null) {
     93             df = new SimpleDateFormat(getDatePattern());
     94             returnValue = df.format(aDate);
     95         }
     96         return returnValue;
     97     }
     98 
     99     /**
    100      * This method generates a string representation of a date/time in the
    101      * format you specify on input
    102      * 
    103      * @param aMask
    104      *            the date pattern the string is in
    105      * @param strDate
    106      *            a string representation of a date
    107      * @return a converted Date object
    108      * @see java.text.SimpleDateFormat
    109      * @throws ParseException
    110      */
    111     public static final Date convertStringToDate(String aMask, String strDate) throws ParseException {
    112         SimpleDateFormat df = null;
    113         Date date = null;
    114         df = new SimpleDateFormat(aMask);
    115         try {
    116             date = df.parse(strDate);
    117         } catch (ParseException pe) {
    118             throw new ParseException(pe.getMessage(), pe.getErrorOffset());
    119         }
    120         return (date);
    121     }
    122     
    123     public static Date convertXMLGregorianCalendar(XMLGregorianCalendar xmlcal) {
    124         GregorianCalendar grecal = xmlcal.toGregorianCalendar();
    125         return grecal.getTime();
    126     }
    127 
    128     public static XMLGregorianCalendar getXMLGregorianCalendar() {
    129 
    130         try {
    131             DatatypeFactory dtf = DatatypeFactory.newInstance();
    132             GregorianCalendar gcal = (GregorianCalendar) GregorianCalendar.getInstance();
    133             return dtf.newXMLGregorianCalendar(gcal);
    134         } catch (DatatypeConfigurationException e) {
    135             return null;
    136         }
    137     }
    138 
    139     public static XMLGregorianCalendar getXMLGregorianCalendarDate(Date date) throws DatatypeConfigurationException {
    140         GregorianCalendar c = new GregorianCalendar();
    141         c.setTime(date);
    142         XMLGregorianCalendar xmlGdate = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
    143         return xmlGdate;
    144     }
    145 
    146     public static long getTimeAlong(Date before, Date after) {
    147         return after.getTime() - before.getTime();
    148     }
    149 
    150     /**
    151      * This method returns the current date time in the format: MM/dd/yyyy HH:MM
    152      * a
    153      * 
    154      * @param theTime
    155      *            the current time
    156      * @return the current date/time
    157      */
    158     public static String getTimeNow(Date theTime) {
    159         return getDateTime(timePattern, theTime);
    160     }
    161 
    162     /**
    163      * This method returns the current date in the format: MM/dd/yyyy
    164      * 
    165      * @return the current date
    166      * @throws ParseException
    167      */
    168     public static Calendar getToday() throws ParseException {
    169         Date today = new Date();
    170         SimpleDateFormat df = new SimpleDateFormat(getDatePattern());
    171 
    172         String todayAsString = df.format(today);
    173         Calendar cal = new GregorianCalendar();
    174         cal.setTime(convertStringToDate(todayAsString));
    175 
    176         return cal;
    177     }
    178 
    179     /**
    180      * 最通用的时间方式
    181      * 
    182      * 
    183      * @param type
    184      *            :样式,如:"yyyy-MM-dd HH:mm:ss.SSS"
    185      * 
    186      */
    187     public static String getDateTime(String type) {
    188         Date aDate = DateUtil.currentSQLDate();
    189 
    190         SimpleDateFormat df = null;
    191         String returnValue = "";
    192         if (aDate != null) {
    193             df = new SimpleDateFormat(type);
    194             returnValue = df.format(aDate);
    195         }
    196         return (returnValue);
    197 
    198     }
    199     
    200     /**
    201      * This method generates a string representation of a date's date/time in
    202      * the format you specify on input
    203      * 
    204      * @param aMask
    205      *            the date pattern the string is in
    206      * @param aDate
    207      *            a date object
    208      * @return a formatted string representation of the date
    209      * 
    210      * @see java.text.SimpleDateFormat
    211      */
    212     public static final String getDateTime(String aMask, Date aDate) {
    213         SimpleDateFormat df = null;
    214         String returnValue = "";
    215         if (aDate != null) {
    216             df = new SimpleDateFormat(aMask);
    217             returnValue = df.format(aDate);
    218         }
    219         return (returnValue);
    220     }
    221     
    222     /**
    223      * This method generates a string representation of a date based on the
    224      * System Property 'dateFormat' in the format you specify on input
    225      * 
    226      * @param aDate
    227      *            A date to convert
    228      * @return a string representation of the date
    229      */
    230     public static final String convertDateToString(Date aDate) {
    231         return getDateTime(getDatePattern(), aDate);
    232     }
    233 
    234     /**
    235      * This method converts a String to a date using the datePattern
    236      * 
    237      * @param strDate
    238      *            the date to convert (in format MM/dd/yyyy)
    239      * @return a date object
    240      * 
    241      * @throws ParseException
    242      */
    243     public static Date convertStringToDate(String strDate) throws ParseException {
    244         Date aDate = null;
    245         try {
    246             aDate = convertStringToDate(getDatePattern(), strDate);
    247         } catch (ParseException pe) {
    248             pe.printStackTrace();
    249             throw new ParseException(pe.getMessage(), pe.getErrorOffset());
    250         }
    251         return aDate;
    252     }
    253 
    254     public static java.sql.Timestamp currentSQLTimestamp() {
    255         return new java.sql.Timestamp(System.currentTimeMillis());
    256     }
    257 
    258     public static synchronized java.sql.Date currentSQLDate() {
    259         return new java.sql.Date(System.currentTimeMillis());
    260     }
    261 
    262     public static java.sql.Date getSQLDate(java.util.Date date) {
    263         return new java.sql.Date(date.getTime());
    264     }
    265 
    266     public static java.sql.Timestamp getSQLTimestamp(java.util.Date date) {
    267         return new java.sql.Timestamp(date.getTime());
    268     }
    269 
    270     public static java.util.Date toDate(String strValue) {
    271         SimpleDateFormat fmt = null;
    272         if (strValue.indexOf('.') > 0) {
    273             fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.CHINA);// 2005-01-01
    274         } else if (strValue.indexOf(':') > 0) {
    275             fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);// 2005-01-01
    276                                                                             // 10:10:10.100
    277         } else if (strValue.indexOf('-') > 0) {
    278             fmt = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);// 2005-01-01
    279         }
    280         try {
    281             return fmt.parse(strValue);
    282         } catch (Exception ex) {
    283             return new Date();// 返回1970-01-01 00:00:00
    284         }
    285     }
    286 
    287     public static java.sql.Timestamp toSQLTimestamp(String strValue) {
    288         return (new java.sql.Timestamp(toDate(strValue).getTime()));
    289     }
    290 
    291     public static String getSQLDateTimeStr(java.util.Date date) {
    292         java.sql.Date sql_date = new java.sql.Date(date.getTime());
    293         java.sql.Time sql_time = new java.sql.Time(date.getTime());
    294         return sql_date + " " + sql_time;
    295     }
    296 
    297     public static boolean comparableBefore(String strValue01, String strValue02) {
    298         return toSQLTimestamp(strValue01).before(toSQLTimestamp(strValue02));
    299     }
    300 
    301     public static boolean comparableAfter(String strValue01, String strValue02) {
    302         return toSQLTimestamp(strValue01).after(toSQLTimestamp(strValue02));
    303     }
    304 
    305     // 根据字符串返回该字符串对应的时间类型"00-00-00 00:00:00"
    306     public static String getbegintime(String begintime) {
    307         return getBegintime(begintime);
    308     }
    309     public static String getBegintime(String begintime) {
    310         if (begintime != null && begintime.length() == 8) {
    311             String yearString = begintime.substring(0, 4);
    312             String monthString = begintime.substring(4, 6);
    313             String dateString = begintime.substring(6);
    314             begintime = yearString + "-" + monthString + "-" + dateString + " " + "00:00:00";
    315         }
    316         return begintime;
    317     }
    318 
    319     // 根据字符串返回该字符串对应的时间类型"00-00-00 24:00:00"
    320     public static String getEndtime(String endtime) {
    321         if (endtime != null && endtime.length() == 8) {
    322             String yearString = endtime.substring(0, 4);
    323             String monthString = endtime.substring(4, 6);
    324             String dateString = endtime.substring(6);
    325             endtime = yearString + "-" + monthString + "-" + dateString + " " + "24:00:00";
    326         }
    327         return endtime;
    328     }
    329 
    330     // 根据字符串返回该字符串对应的日期类型"00-00-00"
    331     public static String getdate(String stringtime) {
    332         if (stringtime != null && stringtime.length() == 8) {
    333             String yearString = stringtime.substring(0, 4);
    334             String monthString = stringtime.substring(4, 6);
    335             String dateString = stringtime.substring(6);
    336             stringtime = yearString + "-" + monthString + "-" + dateString;
    337         }
    338         return stringtime;
    339     }
    340 
    341     // 将2010-10-10类型转换成20101010格式
    342     public static String getString(String stringtime) {
    343         if (stringtime != null && stringtime.length() == 10) {
    344             String yearString = stringtime.substring(0, 4);
    345             String monthString = stringtime.substring(5, 7);
    346             String dateString = stringtime.substring(8);
    347             stringtime = yearString + monthString + dateString;
    348         }
    349         return stringtime;
    350     }
    351 
    352     // 将日期转化为HH24MMSS格式的字符串
    353     public static String convertTohh24mmssFormat(Date date) {
    354         Calendar calendar = Calendar.getInstance();
    355         calendar.setTime(date);
    356         String hour = String.valueOf(calendar.get(Calendar.HOUR_OF_DAY));
    357         if (Integer.parseInt(hour) < 10) {
    358             hour = "0" + hour;
    359         }
    360         String minute = String.valueOf(calendar.get(Calendar.MINUTE));
    361         if (Integer.parseInt(minute) < 10) {
    362             minute = "0" + minute;
    363         }
    364         String second = String.valueOf(calendar.get(Calendar.SECOND));
    365         if (Integer.parseInt(second) < 10) {
    366             second = "0" + second;
    367         }
    368         String result = hour + minute + second;
    369         return result;
    370     }
    371 
    372     // 获得两个日期的时间差,返回结果为_小时_分钟_秒
    373     public static String gettimedefferent(long milliseconds) {
    374         long hours = 0;
    375         long minutes = 0;
    376         long seconds = milliseconds / 1000;
    377         hours = seconds / 3600;
    378         seconds = seconds - hours * 3600;
    379         minutes = seconds / 60;
    380         seconds = seconds - minutes * 60;
    381         System.out.println(hours + "小时" + minutes + "分钟" + seconds + "秒");
    382         return hours + "小时" + minutes + "分钟" + seconds + "秒";
    383     }
    384 
    385     /**
    386      * 获得几秒前的时间
    387      * @param date1 时间 yyyy-MM-dd HH:mm:ss
    388      * @param seconds 秒 1
    389      * @throws ParseException 
    390      */
    391     public static String getTimeBefore(String date1, int seconds) throws ParseException{
    392         DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    393         Date date = df.parse(date1);// 解析成日期格式
    394         date.setTime(date.getTime() - seconds * 1000);// 减去N秒的时间
    395 
    396         return df.format(date);// 再将该时间转换成字符串格式
    397     }
    398     
    399     
    400     /**
    401      * 得到几天后的时间 *
    402      * 
    403      * @param d
    404      * @param day
    405      * @return
    406      */
    407     public static Date getDateAfter(Date d, int day) {
    408         Calendar now = Calendar.getInstance();
    409         now.setTime(d);
    410         now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
    411         return now.getTime();
    412     }
    413 
    414     /**
    415      * 标准日期时间比较大小
    416      * @param String
    417      *            date1 "2014-3-14 18:47:08"
    418      * @param String
    419      *            date2 "2014-3-14 18:47:09"
    420      * @return 毫秒数 1000(ms)
    421      */
    422     public static long diffDateTime(String date1, String date2) {
    423         DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    424         long diff = 0;
    425         try {
    426             Date d1 = df.parse(date1);
    427             Date d2 = df.parse(date2);
    428             diff = d1.getTime() - d2.getTime();
    429         } catch (Exception e) {
    430         }
    431         return diff;
    432     }
    433 
    434     public static String formatLongToTimeStr(Long l) {
    435         int hour = 0;
    436         int minute = 0;
    437         int second = 0;
    438         second = l.intValue() / 1000;
    439 
    440         if (second > 60) {
    441             minute = second / 60;
    442             second = second % 60;
    443         }
    444         if (minute > 60) {
    445             hour = minute / 60;
    446             minute = minute % 60;
    447         }
    448         return (getTwoLength(hour) + getTwoLength(minute) + getTwoLength(second));
    449     }
    450 
    451     public static String getTwoLength(final int data) {
    452         if (data < 10) {
    453             return "0" + data;
    454         } else {
    455             return "" + data;
    456         }
    457     }
    458 
    459     /**
    460      * 将时长转换为分钟
    461      */
    462     public static String change2Minute(String duration) {
    463         if (duration.indexOf(":") >= 0) {
    464             String[] durationArr = duration.split(":");
    465             long hour = Long.parseLong(durationArr[0]);
    466             long minute = Long.parseLong(durationArr[1]);
    467             long second = Long.parseLong(durationArr[2]);
    468             if (second > 0) {
    469                 duration = String.valueOf(hour * 60 + minute + 1);
    470             } else {
    471                 duration = String.valueOf(hour * 60 + minute);
    472             }
    473         } else if (duration.matches("[0-9]+")) {
    474 
    475         } else {
    476             System.out.println("格式不正确:" + duration);
    477         }
    478         return duration;
    479     }
    480     
    481     /**
    482      * 获取当前标准日期时间 
    483      */
    484     public static String getStandardNow() {
    485         return DateUtil.getDateTime("yyyy-MM-dd HH:mm:ss");
    486     }
    487 
    488     /**
    489      * 获取运行时间 
    490      * @param adddays为延期天数
    491      */
    492     public static String getStandardRound(String adddays) {
    493         return getStandardRound(adddays, true);
    494     }
    495 
    496     /**
    497      * 获取运行时间 当前时间标准返回,未来时间只保留日期,时间为00:00:00
    498      * @param adddays 延期天数
    499      * @param readspecial 是否读取特殊含义值 keep 永不失效 将原值返回
    500      * @return
    501      */
    502     public static String getStandardRound(String adddays, boolean readspecial) {
    503         String runDate = new String();
    504         if ("".equals(adddays)) {
    505             adddays = "0";
    506         }
    507         if ("keep".equals(adddays)) {
    508             if (readspecial) {
    509                 return "keep";
    510             } else {
    511                 adddays = "0";
    512             }
    513         }
    514         if ("永不失效".equals(adddays)) {
    515             if (readspecial) {
    516                 return "永不失效";
    517             } else {
    518                 adddays = "0";
    519             }
    520         }
    521         /*
    522          * Pattern
    523          * pattern=Pattern.compile("\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}");
    524          * Matcher matcher=pattern.matcher(runtime); if(matcher.find()){ runDate
    525          * = runtime; //已经是一个完成的时间格式yyyy-MM-dd HH:mm:ss }
    526          */
    527         if (adddays.indexOf(":") != -1) {
    528             runDate = adddays; // 已经是一个完成的时间格式yyyy-MM-dd HH:mm:ss
    529         } else {
    530             adddays = adddays.trim().replace("+", "").trim();
    531             runDate = DateUtil.getDateTime("yyyy-MM-dd HH:mm:ss");
    532             try {
    533                 runDate = DateUtil.convertDateToString(DateUtil.getDateAfter(DateUtil.convertStringToDate(DateUtil.getDateTime("MM/dd/yyyy")),
    534                         Integer.valueOf(adddays)));
    535                 runDate = runDate.substring(6, 10) + "-" + runDate.substring(0, 2) + "-" + runDate.substring(3, 5) + " ";
    536                 if (Integer.valueOf(adddays) == 0) {
    537                     runDate += DateUtil.getDateTime("HH:mm:ss");
    538                 } else {
    539                     runDate += "00:00:00";
    540                 }
    541             } catch (ParseException e) {
    542                 e.printStackTrace();
    543                 return runDate;
    544             }
    545         }
    546         return runDate;
    547     }
    548 
    549     /**
    550      * 判断是否达到指定标准时间
    551      * @param date 2014-01-12 15:00:00
    552      * @return 达到true 未达到false
    553      */
    554     public static boolean isreachStandard(String date) {
    555         // 将仅含日期的date添加上时间
    556         if (date != null && date.length() == 10 && "-".equals(String.valueOf(date.charAt(4))) && "-".equals(String.valueOf(date.charAt(7)))) {
    557             date += " 00:00:00";
    558         }
    559         if (date == null || "null".equals(date) || date.length() != 19) {
    560             return false;
    561         }
    562         String nowdate = getStandardRound("0");
    563         if (nowdate.compareTo(date) < 0) {
    564             return false;
    565         } else {
    566             return true;
    567         }
    568     }
    569 
    570     /**
    571      * 标准时长转为秒数
    572      * @param type : 26:15:04 -> 94504
    573      */
    574     public static long standardtime2secondslong(String duration) {
    575         long sum = 0;
    576         try {
    577             if (duration != null && duration.indexOf(":") >= 0) {
    578                 String[] durationArr = duration.split(":");
    579                 Long hour = Long.parseLong(durationArr[0]);
    580                 Long minute = Long.parseLong(durationArr[1]);
    581                 Long second = Long.parseLong(durationArr[2]);
    582                 sum = hour * 3600 + minute * 60 + second;
    583             }
    584         } catch (Exception e) {
    585             e.printStackTrace();
    586         }
    587         return sum;
    588     }
    589 
    590     /**
    591      * 秒数转为标准时长
    592      * @param type : 94504 -> 26:15:04
    593      * 
    594      */
    595     public static String seconds2standardtime(Long seconds) {
    596         Long second = seconds % 60;
    597         Long minute = (seconds % 3600 - second) / 60;
    598         Long hour = (seconds - minute * 60 - second) / 3600;
    599         return hour + ":" + (minute >= 10 ? minute : "0" + minute) + ":" + (second >= 10 ? second : "0" + second);
    600     }
    601 
    602     /**
    603      * 将yyyyMMdd格式的日期转换为标准格式
    604      * @param type : 20150105 -> 2015-01-05
    605      * @return
    606      */
    607     public static String yyyyMMdd2StandardDate(String stringdate) {
    608         if (stringdate != null && stringdate.length() == 8) {
    609             String yearString = stringdate.substring(0, 4);
    610             String monthString = stringdate.substring(4, 6);
    611             String dateString = stringdate.substring(6, 8);
    612             stringdate = yearString + "-" + monthString + "-" + dateString;
    613         }
    614         return stringdate;
    615     }
    616 
    617     /**
    618      * 将获取的时间转换为标准时间
    619      * @param type : 135000 -> 13:50:00
    620      */
    621     public static String HHmmss2StandardTime(String HH24mmss) {
    622         if (HH24mmss != null && HH24mmss.length() == 6) {
    623             String hourString = HH24mmss.substring(0, 2);
    624             String minuteString = HH24mmss.substring(2, 4);
    625             String secondsString = HH24mmss.substring(4, 6);
    626             HH24mmss = hourString + ":" + minuteString + ":" + secondsString;
    627         }
    628         return HH24mmss;
    629     }
    630 
    631     /**
    632      * 获取某标准日期时间节点经过某时长后的时间节点
    633      * 例初始时间节点: 2014-12-31 23:00:00
    634      * 经过时长:15:00:00
    635      * @return 2015-01-01 14:00:00
    636      */
    637     public static String StandardaddHHmmss(String starttime, String duration) {
    638         int durationtime = (int) DateUtil.standardtime2secondslong(duration);
    639         String endtime = starttime;
    640         // int starthour = Integer.parseInt(starttime.substring(11,12));
    641         // int startminute = Integer.parseInt(starttime.substring(14,15));
    642         //
    643         // int durationhour = Integer.parseInt(duration.substring(0,1));
    644         // int durationminute = Integer.parseInt(duration.substring(3,4));
    645 
    646         // starttime = starttime.substring(11,18);
    647         // if(starttime)
    648         // String endtime = ;
    649         try {
    650             SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    651             Date date = sdf.parse(starttime);
    652             Calendar calendar = Calendar.getInstance();
    653             calendar.setTime(date);
    654             calendar.add(Calendar.SECOND, durationtime);// 对秒数进行操作
    655 
    656             endtime = sdf.format(calendar.getTime());
    657         } catch (ParseException e) {
    658             e.printStackTrace();
    659         }
    660 
    661         return endtime;
    662     }
    663     
    664     public static String formatDate(Date date,String formatter){
    665         try{
    666             SimpleDateFormat sdf = new SimpleDateFormat(formatter);
    667             return sdf.format(date);
    668         }catch(Throwable e){
    669             return "";
    670         }
    671     }
    672 
    673     public static String formatDateWithT(Date date,String formatter){
    674         try{
    675             SimpleDateFormat sdf = new SimpleDateFormat(formatter);
    676             String temp = sdf.format(date);
    677             temp = temp.replace(" ", "T");
    678             return temp;
    679         }catch(Throwable e){
    680             return "";
    681         }
    682     }
    683     
    684     public static Calendar formatString2Date(String date,String formateer){
    685         SimpleDateFormat format1 = new SimpleDateFormat(formateer);  
    686         try {
    687             Date temp =  format1.parse(date);
    688             Calendar cal = Calendar.getInstance();
    689             cal.setTime(temp);
    690             return cal;
    691         } catch (ParseException e) {
    692             return null;
    693         }
    694     }
    695     
    696     public static Calendar formatString2DateWithT(String date,String formateer){
    697         date = date.replace("T", " ");
    698         SimpleDateFormat format1 = new SimpleDateFormat(formateer);  
    699         try {
    700             Date temp =  format1.parse(date);
    701             Calendar cal = Calendar.getInstance();
    702             cal.setTime(temp);
    703             return cal;
    704         } catch (ParseException e) {
    705             return null;
    706         }
    707     }
    708     
    709     public static String getTransactionID(){
    710         Calendar cal = Calendar.getInstance();
    711         String transactionID = "" + cal.get(Calendar.YEAR) + cal.get(Calendar.MONTH) + cal.get(Calendar.DAY_OF_MONTH) + cal.get(Calendar.HOUR_OF_DAY) + cal.get(Calendar.MINUTE) + cal.get(Calendar.SECOND) ;
    712         return transactionID;
    713     }
    714     
    715     // 计算间隔时间
    716     public String intervalTime(String beginTime, String endTime) throws ParseException{
    717         SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    718         java.util.Date beginTimeDate = df.parse(beginTime);
    719         java.util.Date endTimeDate = df.parse(endTime);
    720         
    721         long l = endTimeDate.getTime() - beginTimeDate.getTime();
    722         long day = l / (24 * 60 * 60 * 1000);
    723         long hour = (l / (60 * 60 * 1000) - day * 24);
    724         long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
    725         long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
    726         
    727         return day + "天" + hour + "小时" + min + "分" + s + "秒";
    728     }
    729     
    730     public static void main(String[] args) throws ParseException {
    731 //        String startDate = "2014-09-22";
    732 //        String startTime = "2014-09-22 09:05:02";
    733 //        String endTime = "2014-09-22 12:00:00";
    734 
    735         System.out.println(yyyyMMdd2StandardDate("20140102"));
    736         System.out.println(HHmmss2StandardTime("151617"));
    737         System.out.println(StandardaddHHmmss("2014-12-31 23:00:00","15:00:00"));
    738         
    739         
    740         System.out.println("2015-04-24 11:00:00" + isreachStandard("2015-04-24 11:00:00"));
    741         System.out.println("2011-04-23" + isreachStandard("2011-04-23"));
    742         System.out.println("EMPTY" + isreachStandard(""));
    743         System.out.println("123" + isreachStandard("123"));
    744         System.out.println(isreachStandard(null));
    745 //        
    746 //        Calendar cal = Calendar.getInstance();
    747 //        String s = formatDate(cal.getTime(),"yyyy-MM-ddThh:mm:ss");
    748 //        String s1 = formatDateWithT(cal.getTime(),"yyyy-MM-dd HH:mm:ss");
    749 //        
    750 //        System.out.println(s + "
    " + s1 + "
    " + new Timestamp(cal.getTime().getTime()));
    751         System.out.println("2011-04-23".length());
    752 
    753         // 计算间隔时间
    754         DateUtil dateUtil = new DateUtil();
    755         String beginTime = "2009-02-28 11:30:41";
    756         String endTime = "2009-03-01 13:31:40";
    757         String str = dateUtil.intervalTime(beginTime,endTime);
    758         System.out.println(str);
    759 
    760     }
    761 }
  • 相关阅读:
    js模板
    block,inline和inline-block概念和区别
    jquery parent和parents,children和find
    (CVE-2015-5254)ActiveMQ 反序列化漏洞复现
    办公系统致远OA漏洞
    CVE-2018-16509 GhostScript 沙箱绕过(命令执行)漏洞
    phpmyadmin-相关漏洞详解
    XXL-JOB(任务调度中心)-反弹getshell
    组策略(域和域服务的搭建)
    解决在NAT模式下物理机无法ping通虚拟机的问题
  • 原文地址:https://www.cnblogs.com/DreamDrive/p/5762465.html
Copyright © 2011-2022 走看看