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