View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.util;
8   
9   import org.mule.config.i18n.CoreMessages;
10  
11  import java.text.ParsePosition;
12  import java.text.SimpleDateFormat;
13  import java.util.Date;
14  
15  /**
16   * <code>DateUtils</code> contains some useful methods dealing date/time
17   * conversion, formatting etc.
18   */
19  // @ThreadSafe
20  public class DateUtils extends org.apache.commons.lang.time.DateUtils
21  {
22  
23      public static String getTimeStamp(String format)
24      {
25          // Format the current time.
26          SimpleDateFormat formatter = new SimpleDateFormat(format);
27          Date currentTime = new Date();
28          return formatter.format(currentTime);
29      }
30  
31      public static String formatTimeStamp(Date dateTime, String format)
32      {
33          // Format the current time.
34          SimpleDateFormat formatter = new SimpleDateFormat(format);
35          return formatter.format(dateTime);
36      }
37  
38      public static String getStringFromDate(Date date, String format)
39      {
40          // converts from date to strin using the standard TIME_STAMP_FORMAT
41          // pattern
42          SimpleDateFormat formatter = new SimpleDateFormat(format);
43          return formatter.format(date);
44      }
45  
46      public static Date getDateFromString(String date, String format)
47      {
48          // The date must always be in the format of TIME_STAMP_FORMAT
49          // i.e. JAN 29 2001 22:50:40 GMT
50          SimpleDateFormat formatter = new SimpleDateFormat(format);
51          ParsePosition pos = new ParsePosition(0);
52  
53          // Parse the string back into a Time Stamp.
54          return formatter.parse(date, pos);
55      }
56  
57      public static String getFormattedDuration(long mills)
58      {
59          long days = mills / 86400000;
60          mills = mills - (days * 86400000);
61          long hours = mills / 3600000;
62          mills = mills - (hours * 3600000);
63          long mins = mills / 60000;
64          mills = mills - (mins * 60000);
65          long secs = mills / 1000;
66          mills = mills - (secs * 1000);
67  
68          StringBuffer bf = new StringBuffer(60);
69          bf.append(days).append(" ").append(CoreMessages.days().getMessage()).append(", ");
70          bf.append(hours).append(" ").append(CoreMessages.hours().getMessage()).append(", ");
71          bf.append(mins).append(" ").append(CoreMessages.minutes().getMessage()).append(", ");
72          bf.append(secs).append(".").append(mills).append(" ").append(CoreMessages.seconds().getMessage());
73          return bf.toString();
74      }
75  
76  }