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