View Javadoc
1   /**
2    * This file Copyright (c) 2003-2014 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 HH_MM_SS = "HH:mm:ss";
83  
84      public static final String YYYY_MM_DD_T_HH_MM_SS = "yyyy-MM-dd' 'HH:mm:ss";
85  
86      public static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("UTC");
87  
88      /**
89       * This is a util.
90       */
91      private DateUtil() {
92      }
93  
94      /**
95       * Supports implicit formats like: date, date long, datetime, dateime long, time and time long.
96       */
97      public static String format(Date date, String formatPattern) {
98          return format(date, formatPattern, Locale.getDefault());
99      }
100 
101     public static String format(Date date, String formatPattern, Locale locale) {
102         if(date == null){
103             return StringUtils.EMPTY;
104         }
105 
106         if (formatPattern == null) {
107             formatPattern = FORMAT_DEFAULTPATTERN;
108         }
109 
110         if(FORMAT_DATE_SHORT.equals(formatPattern)){
111             return SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT, locale).format(date);
112         }
113         else if (FORMAT_DATE_MEDIUM.equals(formatPattern)){
114             return SimpleDateFormat.getDateInstance(SimpleDateFormat.MEDIUM, locale).format(date);
115         }
116         else if (FORMAT_DATE_LONG.equals(formatPattern)){
117             return SimpleDateFormat.getDateInstance(SimpleDateFormat.LONG, locale).format(date);
118         }
119         else if (FORMAT_TIME_SHORT.equals(formatPattern)){
120             return SimpleDateFormat.getTimeInstance(SimpleDateFormat.SHORT,locale).format(date);
121         }
122         else if (FORMAT_TIME_MEDIUM.equals(formatPattern)){
123             return SimpleDateFormat.getTimeInstance(SimpleDateFormat.MEDIUM,locale).format(date);
124         }
125         else if (FORMAT_TIME_LONG.equals(formatPattern)){
126             return SimpleDateFormat.getTimeInstance(SimpleDateFormat.LONG,locale).format(date);
127         }
128         else if (FORMAT_DATETIME_SHORT.equals(formatPattern)){
129             return SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT,SimpleDateFormat.SHORT,locale).format(date);
130         }
131         else if (FORMAT_DATETIME_MEDIUM.equals(formatPattern)){
132             return SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.MEDIUM, SimpleDateFormat.MEDIUM, locale).format(date);
133         }
134         else if (FORMAT_DATETIME_LONG.equals(formatPattern)){
135             return SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.LONG, SimpleDateFormat.LONG, locale).format(date);
136         }
137         else {
138             return DateFormatUtils.format(date, formatPattern, locale);
139         }
140     }
141 
142     /**
143      * Uses the current locale (user) to format the date and time.
144      * @param val Date or Calendar
145      * @return the String
146      */
147     public static String formatDateTime(Object val) {
148         if(val == null){
149             return StringUtils.EMPTY;
150         }
151         FastDateFormat format = FastDateFormat.getDateTimeInstance(
152             FastDateFormat.SHORT,
153             FastDateFormat.SHORT,
154             MgnlContext.getLocale());
155         return format.format(val);
156     }
157 
158     /**
159      * Uses the current locale (user) to format the date.
160      * @param val Date or Calendar
161      * @return the String
162      */
163     public static String formatDate(Object val) {
164         if(val == null){
165             return StringUtils.EMPTY;
166         }
167         FastDateFormat format = FastDateFormat.getDateInstance(
168             FastDateFormat.SHORT,
169             MgnlContext.getLocale());
170         return format.format(val);
171     }
172 
173     /**
174      * Uses the current locale (user) to parse the date and time.
175      * @param val Date or Calendar
176      * @return the String
177      * @throws ParseException
178      */
179     public static Date parseDateTime(String dateStr) throws ParseException {
180         DateFormat format = SimpleDateFormat.getDateTimeInstance(
181             FastDateFormat.SHORT,
182             FastDateFormat.SHORT,
183             MgnlContext.getLocale());
184         return (Date)format.parseObject(dateStr);
185     }
186 
187     /**
188      * Uses the current locale (user) to parse the date.
189      * @param val Date or Calendar
190      * @return the String
191      * @throws ParseException
192      */
193     public static Date parseDate(String dateStr) throws ParseException {
194         DateFormat format = SimpleDateFormat.getDateInstance(
195             FastDateFormat.SHORT,
196             MgnlContext.getLocale());
197         return format.parse(dateStr);
198     }
199 
200     /**
201      * Get the equivalent UTC calendar to a local calendar.
202      */
203     public static Calendar getLocalCalendarFromUTC(Calendar utc) {
204         Date valueDate = utc.getTime();
205         Calendar c = Calendar.getInstance(); // this has the default timezone for the server
206         c.setTime(valueDate);
207         return c;
208     }
209 
210     /**
211      * Convert a string date from a dialog date to a UTC calendar ready to be stored in the repository.
212      */
213     public static Calendar getUTCCalendarFromDialogString(String dateString) throws ParseException {
214         SimpleDateFormat sdf = (dateString.length() > YYYY_MM_DD.length())
215             ? new SimpleDateFormat(YYYY_MM_DD_T_HH_MM_SS)
216             : new SimpleDateFormat(YYYY_MM_DD);
217         return getUTCCalendarFromLocalDate(sdf.parse(dateString));
218     }
219 
220     /**
221      * Convert a string date from a dialog date to a UTC calendar ready to be stored in the repository.
222      */
223     public static Calendar getUTCCalendarFromDialogString(String dateString, String format) throws ParseException {
224         SimpleDateFormat sdf = new SimpleDateFormat(format);
225         return getUTCCalendarFromLocalDate(sdf.parse(dateString));
226     }
227 
228     /**
229      * Convert a local date time to a UTC calendar.
230      */
231     public static Calendar getUTCCalendarFromLocalDate(Date date) {
232         Calendar instance = getCurrentUTCCalendar();
233         instance.setTimeInMillis(date.getTime());
234         return instance;
235     }
236 
237     /**
238      * Get UTC Calendar for current time.
239      */
240     public static Calendar getCurrentUTCCalendar() {
241         return Calendar.getInstance(UTC_TIME_ZONE);
242     }
243 
244     /**
245      * Expression for searching - representing a date.
246      */
247     public static String createDateExpression(Calendar calendar) {
248         return "DATE '" + DateFormatUtils.format(calendar.getTimeInMillis(), "yyyy-MM-dd", calendar.getTimeZone()) + "'";
249     }
250 
251     /**
252      * Expression for searching - representing a date and time.
253      */
254     public static String createDateTimeExpression(Calendar calendar) {
255         calendar.set(Calendar.MILLISECOND, 0);
256         StringBuffer str = new StringBuffer("TIMESTAMP '");
257         str.append(DateFormatUtils.format(calendar.getTime(), "yyyy-MM-dd'T'HH:mm:ss.SSSZ", calendar.getTimeZone()));
258         str.insert(str.length() - 2, ":");
259         str.append("'");
260         return str.toString();
261     }
262 
263     /**
264      * Expression for searching - not considering the timezone.
265      */
266     public static String createDateTimeExpressionIgnoreTimeZone(Calendar calendar) {
267         Calendar utc = Calendar.getInstance(DateUtils.UTC_TIME_ZONE);
268         utc.setTimeInMillis(calendar.getTimeInMillis() + calendar.getTimeZone().getRawOffset());
269         return createDateTimeExpression(utc);
270     }
271 }