View Javadoc

1   /**
2    * This file Copyright (c) 2003-2011 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.cms.util;
35  
36  import info.magnolia.context.MgnlContext;
37  import org.apache.commons.lang.StringUtils;
38  import org.apache.commons.lang.time.DateFormatUtils;
39  import org.apache.commons.lang.time.DateUtils;
40  import org.apache.commons.lang.time.FastDateFormat;
41  
42  import java.text.DateFormat;
43  import java.text.ParseException;
44  import java.text.SimpleDateFormat;
45  import java.util.Calendar;
46  import java.util.Date;
47  import java.util.Locale;
48  import java.util.TimeZone;
49  
50  
51  /**
52   * Util to format and parse dates.
53   * @version $Revision$ ($Author$)
54   */
55  public class DateUtil {
56  
57      public static final String FORMAT_DATE_SHORT = "date short";
58  
59      public static final String FORMAT_DATE_MEDIUM = "date";
60  
61      public static final String FORMAT_DATE_LONG = "date long";
62  
63      public static final String FORMAT_DATETIME_SHORT = "datetime short";
64  
65      public static final String FORMAT_DATETIME_MEDIUM = "datetime";
66  
67      public static final String FORMAT_DATETIME_LONG = "datetime long";
68  
69      public static final String FORMAT_TIME_SHORT = "time short";
70  
71      public static final String FORMAT_TIME_MEDIUM = "time";
72  
73      public static final String FORMAT_TIME_LONG = "time long";
74  
75      /**
76       * Default date format.
77       */
78      public static final String FORMAT_DEFAULTPATTERN = "yyyy-MM-dd'T'HH:mm:ss.SZ"; //$NON-NLS-1$
79  
80      public static final String YYYY_MM_DD = "yyyy-MM-dd";
81  
82      public static final String YYYY_MM_DD_T_HH_MM_SS = "yyyy-MM-dd' 'HH:mm:ss";
83  
84      public static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("UTC");
85  
86      /**
87       * This is a util.
88       */
89      private DateUtil() {
90      }
91  
92      /**
93       * Supports implicit formats like: date, date long, datetime, dateime long, time and time long.
94       */
95      public static String format(Date date, String formatPattern) {
96          return format(date, formatPattern, Locale.getDefault());
97      }
98  
99      public static String format(Date date, String formatPattern, Locale locale) {
100         if(date == null){
101             return StringUtils.EMPTY;
102         }
103 
104         if (formatPattern == null) {
105             formatPattern = FORMAT_DEFAULTPATTERN;
106         }
107 
108         if(FORMAT_DATE_SHORT.equals(formatPattern)){
109             return SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT, locale).format(date);
110         }
111         else if (FORMAT_DATE_MEDIUM.equals(formatPattern)){
112             return SimpleDateFormat.getDateInstance(SimpleDateFormat.MEDIUM, locale).format(date);
113         }
114         else if (FORMAT_DATE_LONG.equals(formatPattern)){
115             return SimpleDateFormat.getDateInstance(SimpleDateFormat.LONG, locale).format(date);
116         }
117         else if (FORMAT_TIME_SHORT.equals(formatPattern)){
118             return SimpleDateFormat.getTimeInstance(SimpleDateFormat.SHORT,locale).format(date);
119         }
120         else if (FORMAT_TIME_MEDIUM.equals(formatPattern)){
121             return SimpleDateFormat.getTimeInstance(SimpleDateFormat.MEDIUM,locale).format(date);
122         }
123         else if (FORMAT_TIME_LONG.equals(formatPattern)){
124             return SimpleDateFormat.getTimeInstance(SimpleDateFormat.LONG,locale).format(date);
125         }
126         else if (FORMAT_DATETIME_SHORT.equals(formatPattern)){
127             return SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT,SimpleDateFormat.SHORT,locale).format(date);
128         }
129         else if (FORMAT_DATETIME_MEDIUM.equals(formatPattern)){
130             return SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.MEDIUM, SimpleDateFormat.MEDIUM, locale).format(date);
131         }
132         else if (FORMAT_DATETIME_LONG.equals(formatPattern)){
133             return SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.LONG, SimpleDateFormat.LONG, locale).format(date);
134         }
135         else {
136             return DateFormatUtils.format(date, formatPattern, locale);
137         }
138     }
139 
140     /**
141      * Uses the current locale (user) to format the date and time.
142      * @param val Date or Calendar
143      * @return the String
144      */
145     public static String formatDateTime(Object val) {
146         if(val == null){
147             return StringUtils.EMPTY;
148         }
149         FastDateFormat format = FastDateFormat.getDateTimeInstance(
150             FastDateFormat.SHORT,
151             FastDateFormat.SHORT,
152             MgnlContext.getLocale());
153         return format.format(val);
154     }
155 
156     /**
157      * Uses the current locale (user) to format the date.
158      * @param val Date or Calendar
159      * @return the String
160      */
161     public static String formatDate(Object val) {
162         if(val == null){
163             return StringUtils.EMPTY;
164         }
165         FastDateFormat format = FastDateFormat.getDateInstance(
166             FastDateFormat.SHORT,
167             MgnlContext.getLocale());
168         return format.format(val);
169     }
170 
171     /**
172      * Uses the current locale (user) to parse the date and time.
173      * @param val Date or Calendar
174      * @return the String
175      * @throws ParseException
176      */
177     public static Date parseDateTime(String dateStr) throws ParseException {
178         DateFormat format = SimpleDateFormat.getDateTimeInstance(
179             FastDateFormat.SHORT,
180             FastDateFormat.SHORT,
181             MgnlContext.getLocale());
182         return (Date)format.parseObject(dateStr);
183     }
184 
185     /**
186      * Uses the current locale (user) to parse the date.
187      * @param val Date or Calendar
188      * @return the String
189      * @throws ParseException
190      */
191     public static Date parseDate(String dateStr) throws ParseException {
192         DateFormat format = SimpleDateFormat.getDateInstance(
193             FastDateFormat.SHORT,
194             MgnlContext.getLocale());
195         return format.parse(dateStr);
196     }
197 
198     /**
199      * Get the equivalent UTC calendar to a local calendar.
200      */
201     public static Calendar getLocalCalendarFromUTC(Calendar utc) {
202         Date valueDate = utc.getTime();
203         Calendar c = Calendar.getInstance(); // this has the default timezone for the server
204         c.setTime(valueDate);
205         return c;
206     }
207 
208     /**
209      * Convert a string date from a dialog date to a UTC calendar ready to be stored in the repository.
210      */
211     public static Calendar getUTCCalendarFromDialogString(String dateString) throws ParseException {
212         SimpleDateFormat sdf = (dateString.length() > YYYY_MM_DD.length())
213             ? new SimpleDateFormat(YYYY_MM_DD_T_HH_MM_SS)
214             : new SimpleDateFormat(YYYY_MM_DD);
215         return getUTCCalendarFromLocalDate(sdf.parse(dateString));
216     }
217 
218     /**
219      * Convert a local date time to a UTC calendar.
220      */
221     public static Calendar getUTCCalendarFromLocalDate(Date date) {
222         Calendar instance = getCurrentUTCCalendar();
223         instance.setTimeInMillis(date.getTime());
224         return instance;
225     }
226 
227     /**
228      * Get UTC Calendar for current time.
229      */
230     public static Calendar getCurrentUTCCalendar() {
231         return Calendar.getInstance(UTC_TIME_ZONE);
232     }
233     
234     /**
235      * Expression for searching - representing a date.
236      */
237     public static String createDateExpression(Calendar calendar) {
238         return "DATE '" + DateFormatUtils.format(calendar.getTimeInMillis(), "yyyy-MM-dd", calendar.getTimeZone()) + "'";
239     }
240     
241     /**
242      * Expression for searching - representing a date and time.
243      */
244     public static String createDateTimeExpression(Calendar calendar) {
245         calendar.set(Calendar.MILLISECOND, 0);
246         StringBuffer str = new StringBuffer("TIMESTAMP '");
247         str.append(DateFormatUtils.format(calendar.getTime(), "yyyy-MM-dd'T'HH:mm:ss.SSSZ", calendar.getTimeZone()));
248         str.insert(str.length() - 2, ":");
249         str.append("'");
250         return str.toString();
251     }
252     
253     /**
254      * Expression for searching - not considering the timezone.
255      */
256     public static String createDateTimeExpressionIgnoreTimeZone(Calendar calendar) {
257         Calendar utc = Calendar.getInstance(DateUtils.UTC_TIME_ZONE);
258         utc.setTimeInMillis(calendar.getTimeInMillis() + calendar.getTimeZone().getRawOffset());
259         return createDateTimeExpression(utc);
260     }
261 }