001    /**
002     * Licensed to the Apache Software Foundation (ASF) under one
003     * or more contributor license agreements.  See the NOTICE file
004     * distributed with this work for additional information
005     * regarding copyright ownership.  The ASF licenses this file
006     * to you under the Apache License, Version 2.0 (the
007     * "License"); you may not use this file except in compliance
008     * with the License.  You may obtain a copy of the License at
009     * 
010     *      http://www.apache.org/licenses/LICENSE-2.0
011     * 
012     * Unless required by applicable law or agreed to in writing, software
013     * distributed under the License is distributed on an "AS IS" BASIS,
014     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015     * See the License for the specific language governing permissions and
016     * limitations under the License.
017     */
018    package org.apache.oozie.util;
019    
020    import java.sql.Timestamp;
021    import java.text.DateFormat;
022    import java.text.ParsePosition;
023    import java.text.SimpleDateFormat;
024    import java.util.Calendar;
025    import java.util.Date;
026    import java.util.GregorianCalendar;
027    import java.util.Locale;
028    import java.util.TimeZone;
029    
030    import org.apache.oozie.coord.TimeUnit;
031    
032    public class DateUtils {
033    
034        private static final String[] W3CDATETIME_MASKS = {"yyyy-MM-dd'T'HH:mmz"};
035    
036        /**
037         * Parses a Date out of a String with a date in W3C date-time format.
038         * <p/>
039         * It parsers the following formats:
040         * <ul>
041         * <li>"yyyy-MM-dd'T'HH:mm:ssz"</li>
042         * <li>"yyyy-MM-dd'T'HH:mmz"</li>
043         * <li>"yyyy-MM-dd"</li>
044         * <li>"yyyy-MM"</li>
045         * <li>"yyyy"</li>
046         * </ul>
047         * <p/>
048         * Refer to the java.text.SimpleDateFormat javadocs for details on the
049         * format of each element.
050         * <p/>
051         *
052         * @param sDate string to parse for a date.
053         * @return the Date represented by the given W3C date-time string. It
054         * returns <b>null</b> if it was not possible to parse the given
055         * string into a Date.
056         */
057        /*
058         * public static Date parseW3CDateTime(String sDate) { // if sDate has time
059         * on it, it injects 'GTM' before de TZ displacement to // allow the
060         * SimpleDateFormat parser to parse it properly int tIndex =
061         * sDate.indexOf("T"); if (tIndex > -1) { if (sDate.endsWith("Z")) { sDate =
062         * sDate.substring(0, sDate.length() - 1) + "+00:00"; } int tzdIndex =
063         * sDate.indexOf("+", tIndex); if (tzdIndex == -1) { tzdIndex =
064         * sDate.indexOf("-", tIndex); } if (tzdIndex > -1) { String pre =
065         * sDate.substring(0, tzdIndex); int secFraction = pre.indexOf(","); if
066         * (secFraction > -1) { pre = pre.substring(0, secFraction); } String post =
067         * sDate.substring(tzdIndex); sDate = pre + "GMT" + post; } } else { sDate
068         * += "T00:00GMT"; } return parseUsingMask(W3CDATETIME_MASKS, sDate); }
069         */
070        /**
071         * Parses a Date out of a string using an array of masks. <p/> It uses the masks in order until one of them succedes
072         * or all fail. <p/>
073         *
074         * @param masks array of masks to use for parsing the string
075         * @param sDate string to parse for a date.
076         * @return the Date represented by the given string using one of the given masks. It returns <b>null</b> if it was
077         *         not possible to parse the the string with any of the masks.
078         */
079        private static Date parseUsingMask(String[] masks, String sDate) {
080            sDate = (sDate != null) ? sDate.trim() : null;
081            ParsePosition pp;
082            Date d = null;
083            if (sDate != null) {
084                for (int i = 0; d == null && i < masks.length; i++) {
085                    DateFormat df = new SimpleDateFormat(masks[i], Locale.US);
086                    df.setLenient(true);
087                    pp = new ParsePosition(0);
088                    d = df.parse(sDate, pp);
089                    if (pp.getIndex() != sDate.length()) {
090                        d = null;
091                    }
092                }
093            }
094            return d;
095        }
096    
097        private static final TimeZone UTC = getTimeZone("UTC");
098    
099        private static DateFormat getISO8601DateFormat() {
100            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
101            dateFormat.setTimeZone(UTC);
102            return dateFormat;
103        }
104        
105        private static DateFormat getSpecificDateFormat(String format) {
106            DateFormat dateFormat = new SimpleDateFormat(format);
107            dateFormat.setTimeZone(UTC);
108            return dateFormat;
109        }
110    
111        public static TimeZone getTimeZone(String tzId) {
112            if (tzId == null) {
113                throw new IllegalArgumentException("Invalid TimeZone: " + tzId);
114            }
115            TimeZone tz = TimeZone.getTimeZone(tzId);
116            if (!tz.getID().equals(tzId)) {
117                throw new IllegalArgumentException("Invalid TimeZone: " + tzId);
118            }
119            return tz;
120        }
121    
122        public static Date parseDateUTC(String s) throws Exception {
123            return getISO8601DateFormat().parse(s);
124        }
125    
126        public static String formatDateUTC(Date d) throws Exception {
127            return (d != null) ? getISO8601DateFormat().format(d) : "NULL";
128        }
129    
130        public static String formatDateCustom(Date d, String format) throws Exception {
131            return (d != null) ? getSpecificDateFormat(format).format(d) : "NULL";
132        }
133    
134        public static String formatDateUTC(Calendar c) throws Exception {
135            return (c != null) ? formatDateUTC(c.getTime()) : "NULL";
136        }
137    
138        /**
139         * This function returns number of hour in a day when given a Calendar with appropriate TZ. It consider DST to find
140         * the number of hours. Generally it is 24. At some tZ, in one day of a year it is 23 and another day it is 25
141         *
142         * @param cal: The date for which the number of hours is requested
143         * @return number of hour in that day.
144         */
145        public static int hoursInDay(Calendar cal) {
146            Calendar localCal = new GregorianCalendar(cal.getTimeZone());
147            localCal.set(Calendar.MILLISECOND, 0);
148            localCal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 30, 0);
149            localCal.add(Calendar.HOUR_OF_DAY, 24);
150            switch (localCal.get(Calendar.HOUR_OF_DAY)) {
151                case 1:
152                    return 23;
153                case 23:
154                    return 25;
155                default: // Case 0
156                    return 24;
157            }
158        }
159    
160        /**
161         * Determine whether a specific date is on DST change day
162         *
163         * @param cal: Date to know if it is DST change day. Appropriate TZ is specified
164         * @return true , if it DST change date otherwise false
165         */
166        public static boolean isDSTChangeDay(Calendar cal) {
167            return hoursInDay(cal) != 24;
168        }
169    
170        /**
171         * Move the any date-time to the end of the duration. If endOfFlag == day, move the date to the end of day (24:00 on
172         * the same day or 00:00 on the next day) If endOf Flag = month. move the date to then end of current month
173         * Otherwise do nothing
174         *
175         * @param cal : Date-time needs to be moved to the end
176         * @param endOfFlag : day (for end of day) or month (for end of month) or empty
177         */
178        public static void moveToEnd(Calendar cal, TimeUnit endOfFlag) {
179            // TODO: Both logic needs to be checked
180            if (endOfFlag == TimeUnit.END_OF_DAY) { // 24:00:00
181                cal.add(Calendar.DAY_OF_MONTH, 1);
182                // cal.set(Calendar.HOUR_OF_DAY, cal
183                // .getActualMaximum(Calendar.HOUR_OF_DAY) + 1);// TODO:
184                cal.set(Calendar.HOUR_OF_DAY, 0);
185                cal.set(Calendar.MINUTE, 0);
186                cal.set(Calendar.SECOND, 0);
187            }
188            else {
189                if (endOfFlag == TimeUnit.END_OF_MONTH) {
190                    cal.add(Calendar.MONTH, 1);
191                    cal.set(Calendar.DAY_OF_MONTH, 1);
192                    cal.set(Calendar.HOUR_OF_DAY, 0);
193                    cal.set(Calendar.MINUTE, 0);
194                    cal.set(Calendar.SECOND, 0);
195                }
196            }
197        }
198    
199        /**
200         * Create a Calendar instance using the specified date and Time zone
201         * @param dateString
202         * @param tz : TimeZone
203         * @return appropriate Calendar object
204         * @throws Exception
205         */
206        public static Calendar getCalendar(String dateString, TimeZone tz) throws Exception {
207            Date date = DateUtils.parseDateUTC(dateString);
208            Calendar calDate = Calendar.getInstance();
209            calDate.setTime(date);
210            calDate.setTimeZone(tz);
211            return calDate;
212        }
213    
214        /**
215         * Create a Calendar instance for UTC time zone using the specified date.
216         * @param dateString
217         * @return appropriate Calendar object
218         * @throws Exception
219         */
220        public static Calendar getCalendar(String dateString) throws Exception {
221            return getCalendar(dateString, DateUtils.getTimeZone("UTC"));
222        }
223    
224        /**
225         * Convert java.sql.Timestamp to java.util.Date
226         *
227         * @param timestamp java.sql.Timestamp
228         * @return java.util.Date
229         */
230        public static java.util.Date toDate(java.sql.Timestamp timestamp) {
231            if (timestamp != null) {
232                long milliseconds = timestamp.getTime();
233                return new java.util.Date(milliseconds);
234            }
235            return null;
236        }
237    
238        /**
239         * Convert java.util.Date to java.sql.Timestamp
240         *
241         * @param d java.util.Date
242         * @return java.sql.Timestamp
243         */
244        public static Timestamp convertDateToTimestamp(Date d) {
245            if (d != null) {
246                return new Timestamp(d.getTime());
247            }
248            return null;
249        }
250    
251        /**
252         * Return the UTC date and time in W3C format down to second
253         * (yyyy-MM-ddTHH:mm:ssZ). i.e.: 1997-07-16T19:20:30Z
254         *
255         * @return the formatted time string.
256         */
257        public static String convertDateToString(Date date) {
258            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
259            sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
260            return sdf.format(date);
261        }
262    
263        /**
264         * Return the UTC date and time in W3C format down to second
265         * (yyyy-MM-ddTHH:mm:ssZ). i.e.: 1997-07-16T19:20:30Z The input date is a
266         * long (Unix Time Stamp)
267         * 
268         * @return the formatted time string.
269         */
270        public static String convertDateToString(long timeStamp) {
271            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
272            sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
273            return sdf.format(new Date(timeStamp));
274        }
275    
276    }