View Javadoc
1   /**
2    * This file Copyright (c) 2003-2018 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  
38  import java.text.DateFormat;
39  import java.text.ParseException;
40  import java.text.SimpleDateFormat;
41  import java.util.Calendar;
42  import java.util.Date;
43  import java.util.Locale;
44  import java.util.TimeZone;
45  
46  import org.apache.commons.lang3.StringUtils;
47  import org.apache.commons.lang3.time.DateFormatUtils;
48  import org.apache.commons.lang3.time.FastDateFormat;
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         } else if (FORMAT_DATE_MEDIUM.equals(formatPattern)) {
110             return SimpleDateFormat.getDateInstance(SimpleDateFormat.MEDIUM, locale).format(date);
111         } else if (FORMAT_DATE_LONG.equals(formatPattern)) {
112             return SimpleDateFormat.getDateInstance(SimpleDateFormat.LONG, locale).format(date);
113         } else if (FORMAT_TIME_SHORT.equals(formatPattern)) {
114             return SimpleDateFormat.getTimeInstance(SimpleDateFormat.SHORT, locale).format(date);
115         } else if (FORMAT_TIME_MEDIUM.equals(formatPattern)) {
116             return SimpleDateFormat.getTimeInstance(SimpleDateFormat.MEDIUM, locale).format(date);
117         } else if (FORMAT_TIME_LONG.equals(formatPattern)) {
118             return SimpleDateFormat.getTimeInstance(SimpleDateFormat.LONG, locale).format(date);
119         } else if (FORMAT_DATETIME_SHORT.equals(formatPattern)) {
120             return SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT, locale).format(date);
121         } else if (FORMAT_DATETIME_MEDIUM.equals(formatPattern)) {
122             return SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.MEDIUM, SimpleDateFormat.MEDIUM, locale).format(date);
123         } else if (FORMAT_DATETIME_LONG.equals(formatPattern)) {
124             return SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.LONG, SimpleDateFormat.LONG, locale).format(date);
125         } else {
126             return DateFormatUtils.format(date, formatPattern, locale);
127         }
128     }
129 
130     /**
131      * Uses the current locale (user) to format the date and time.
132      *
133      * @param val Date or Calendar
134      * @return the String
135      */
136     public static String formatDateTime(Object val) {
137         if (val == null) {
138             return StringUtils.EMPTY;
139         }
140         FastDateFormat format = FastDateFormat.getDateTimeInstance(
141                 FastDateFormat.SHORT,
142                 FastDateFormat.SHORT,
143                 MgnlContext.getLocale());
144         return format.format(val);
145     }
146 
147     /**
148      * Uses the current locale (user) to format the date.
149      *
150      * @param val Date or Calendar
151      * @return the String
152      */
153     public static String formatDate(Object val) {
154         if (val == null) {
155             return StringUtils.EMPTY;
156         }
157         FastDateFormat format = FastDateFormat.getDateInstance(
158                 FastDateFormat.SHORT,
159                 MgnlContext.getLocale());
160         return format.format(val);
161     }
162 
163     /**
164      * Uses the current locale (user) to parse the date and time.
165      *
166      * @param dateStr Date or Calendar
167      * @return the String
168      */
169     public static Date parseDateTime(String dateStr) throws ParseException {
170         DateFormat format = SimpleDateFormat.getDateTimeInstance(
171                 FastDateFormat.SHORT,
172                 FastDateFormat.SHORT,
173                 MgnlContext.getLocale());
174         return (Date) format.parseObject(dateStr);
175     }
176 
177     /**
178      * Uses the current locale (user) to parse the date.
179      *
180      * @param dateStr Date or Calendar
181      * @return the String
182      */
183     public static Date parseDate(String dateStr) throws ParseException {
184         DateFormat format = SimpleDateFormat.getDateInstance(
185                 FastDateFormat.SHORT,
186                 MgnlContext.getLocale());
187         return format.parse(dateStr);
188     }
189 
190     /**
191      * Get the equivalent UTC calendar to a local calendar.
192      */
193     public static Calendar getLocalCalendarFromUTC(Calendar utc) {
194         Date valueDate = utc.getTime();
195         Calendar c = Calendar.getInstance(); // this has the default timezone for the server
196         c.setTime(valueDate);
197         return c;
198     }
199 
200     /**
201      * Convert a string date from a dialog date to a UTC calendar ready to be stored in the repository.
202      */
203     public static Calendar getUTCCalendarFromDialogString(String dateString) throws ParseException {
204         SimpleDateFormat sdf = (dateString.length() > YYYY_MM_DD.length())
205                 ? new SimpleDateFormat(YYYY_MM_DD_T_HH_MM_SS)
206                 : new SimpleDateFormat(YYYY_MM_DD);
207         return getUTCCalendarFromLocalDate(sdf.parse(dateString));
208     }
209 
210     /**
211      * Convert a local date time to a UTC calendar.
212      */
213     public static Calendar getUTCCalendarFromLocalDate(Date date) {
214         Calendar instance = getCurrentUTCCalendar();
215         instance.setTimeInMillis(date.getTime());
216         return instance;
217     }
218 
219     /**
220      * Get UTC Calendar for current time.
221      */
222     public static Calendar getCurrentUTCCalendar() {
223         return Calendar.getInstance(UTC_TIME_ZONE);
224     }
225 
226     /**
227      * Expression for searching - representing a date.
228      */
229     public static String createDateExpression(Calendar calendar) {
230         return "DATE '" + DateFormatUtils.format(calendar.getTimeInMillis(), "yyyy-MM-dd", calendar.getTimeZone()) + "'";
231     }
232 
233     /**
234      * Expression for searching - representing a date and time.
235      */
236     public static String createDateTimeExpression(Calendar calendar) {
237         calendar.set(Calendar.MILLISECOND, 0);
238         StringBuffer str = new StringBuffer("TIMESTAMP '");
239         str.append(DateFormatUtils.format(calendar.getTime(), "yyyy-MM-dd'T'HH:mm:ss.SSSZ", calendar.getTimeZone()));
240         str.insert(str.length() - 2, ":");
241         str.append("'");
242         return str.toString();
243     }
244 
245     /**
246      * Expression for searching - not considering the timezone.
247      */
248     public static String createDateTimeExpressionIgnoreTimeZone(Calendar calendar) {
249         Calendar utc = Calendar.getInstance(UTC_TIME_ZONE);
250         utc.setTimeInMillis(calendar.getTimeInMillis() + calendar.getTimeZone().getRawOffset());
251         return createDateTimeExpression(utc);
252     }
253 }