View Javadoc
1   /*******************************************************************************
2    *   Gisgraphy Project 
3    * 
4    *   This library is free software; you can redistribute it and/or
5    *   modify it under the terms of the GNU Lesser General Public
6    *   License as published by the Free Software Foundation; either
7    *   version 2.1 of the License, or (at your option) any later version.
8    * 
9    *   This library is distributed in the hope that it will be useful,
10   *   but WITHOUT ANY WARRANTY; without even the implied warranty of
11   *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12   *   Lesser General Public License for more details.
13   * 
14   *   You should have received a copy of the GNU Lesser General Public
15   *   License along with this library; if not, write to the Free Software
16   *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
17   * 
18   *  Copyright 2008  Gisgraphy project 
19   *  David Masclet <davidmasclet@gisgraphy.com>
20   *  
21   *  
22   *******************************************************************************/
23  package com.gisgraphy.util;
24  
25  import java.text.ParseException;
26  import java.text.SimpleDateFormat;
27  import java.util.Calendar;
28  import java.util.Date;
29  import java.util.GregorianCalendar;
30  import java.util.Locale;
31  import java.util.MissingResourceException;
32  import java.util.ResourceBundle;
33  
34  import org.apache.commons.logging.Log;
35  import org.apache.commons.logging.LogFactory;
36  import org.springframework.context.i18n.LocaleContextHolder;
37  
38  import com.gisgraphy.domain.valueobject.Constants;
39  
40  /**
41   * Date Utility Class used to convert Strings to Dates and Timestamps
42   * 
43   * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a> Modified by
44   *         <a href="mailto:dan@getrolling.com">Dan Kibler </a> to correct time
45   *         pattern. Minutes should be mm not MM (MM is month).
46   */
47  public class DateUtil {
48      private static Log log = LogFactory.getLog(DateUtil.class);
49  
50      private static final String TIME_PATTERN = "HH:mm";
51  
52      /**
53       * Checkstyle rule: utility classes should not have public constructor
54       */
55      private DateUtil() {
56      }
57  
58      /**
59       * Return default datePattern (MM/dd/yyyy)
60       * 
61       * @return a string representing the date pattern on the UI
62       */
63      public static String getDatePattern() {
64  	Locale locale = LocaleContextHolder.getLocale();
65  	String defaultDatePattern;
66  	try {
67  	    defaultDatePattern = ResourceBundle.getBundle(Constants.BUNDLE_KEY,
68  		    locale).getString("date.format");
69  	} catch (MissingResourceException mse) {
70  	    defaultDatePattern = "MM/dd/yyyy";
71  	}
72  
73  	return defaultDatePattern;
74      }
75  
76      public static String getDateTimePattern() {
77  	return DateUtil.getDatePattern() + " HH:mm:ss.S";
78      }
79  
80      /**
81       * This method attempts to convert an Oracle-formatted date in the form
82       * dd-MMM-yyyy to mm/dd/yyyy.
83       * 
84       * @param aDate
85       *                date from database as a string
86       * @return formatted string for the ui
87       */
88      public static String getDate(Date aDate) {
89  	SimpleDateFormat df;
90  	String returnValue = "";
91  
92  	if (aDate != null) {
93  	    df = new SimpleDateFormat(getDatePattern());
94  	    returnValue = df.format(aDate);
95  	}
96  
97  	return (returnValue);
98      }
99  
100     /**
101      * This method generates a string representation of a date/time in the
102      * format you specify on input
103      * 
104      * @param aMask
105      *                the date pattern the string is in
106      * @param strDate
107      *                a string representation of a date
108      * @return a converted Date object
109      * @see java.text.SimpleDateFormat
110      * @throws ParseException
111      *                 when String doesn't match the expected format
112      */
113     public static Date convertStringToDate(String aMask, String strDate)
114 	    throws ParseException {
115 	SimpleDateFormat df;
116 	Date date;
117 	df = new SimpleDateFormat(aMask);
118 
119 	if (log.isDebugEnabled()) {
120 	    log.debug("converting '" + strDate + "' to date with mask '"
121 		    + aMask + "'");
122 	}
123 
124 	try {
125 	    date = df.parse(strDate);
126 	} catch (ParseException pe) {
127 	    // log.error("ParseException: " + pe);
128 	    throw new ParseException(pe.getMessage(), pe.getErrorOffset());
129 	}
130 
131 	return (date);
132     }
133 
134     /**
135      * This method returns the current date time in the format: MM/dd/yyyy HH:MM
136      * a
137      * 
138      * @param theTime
139      *                the current time
140      * @return the current date/time
141      */
142     public static String getTimeNow(Date theTime) {
143 	return getDateTime(TIME_PATTERN, theTime);
144     }
145 
146     /**
147      * This method returns the current date in the format: MM/dd/yyyy
148      * 
149      * @return the current date
150      * @throws ParseException
151      *                 when String doesn't match the expected format
152      */
153     public static Calendar getToday() throws ParseException {
154 	Date today = new Date();
155 	SimpleDateFormat df = new SimpleDateFormat(getDatePattern());
156 
157 	// This seems like quite a hack (date -> string -> date),
158 	// but it works ;-)
159 	String todayAsString = df.format(today);
160 	Calendar cal = new GregorianCalendar();
161 	cal.setTime(convertStringToDate(todayAsString));
162 
163 	return cal;
164     }
165 
166     /**
167      * This method generates a string representation of a date's date/time in
168      * the format you specify on input
169      * 
170      * @param aMask
171      *                the date pattern the string is in
172      * @param aDate
173      *                a date object
174      * @return a formatted string representation of the date
175      * @see java.text.SimpleDateFormat
176      */
177     public static String getDateTime(String aMask, Date aDate) {
178 	SimpleDateFormat df = null;
179 	String returnValue = "";
180 
181 	if (aDate == null) {
182 	    log.error("aDate is null!");
183 	} else {
184 	    df = new SimpleDateFormat(aMask);
185 	    returnValue = df.format(aDate);
186 	}
187 
188 	return (returnValue);
189     }
190 
191     /**
192      * This method generates a string representation of a date based on the
193      * System Property 'dateFormat' in the format you specify on input
194      * 
195      * @param aDate
196      *                A date to convert
197      * @return a string representation of the date
198      */
199     public static String convertDateToString(Date aDate) {
200 	return getDateTime(getDatePattern(), aDate);
201     }
202 
203     /**
204      * This method converts a String to a date using the datePattern
205      * 
206      * @param strDate
207      *                the date to convert (in format MM/dd/yyyy)
208      * @return a date object
209      * @throws ParseException
210      *                 when String doesn't match the expected format
211      */
212     public static Date convertStringToDate(String strDate)
213 	    throws ParseException {
214 	Date aDate = null;
215 
216 	try {
217 	    if (log.isDebugEnabled()) {
218 		log.debug("converting date with pattern: " + getDatePattern());
219 	    }
220 
221 	    aDate = convertStringToDate(getDatePattern(), strDate);
222 	} catch (ParseException pe) {
223 	    log.error("Could not convert '" + strDate
224 		    + "' to a date, throwing exception");
225 	    throw new ParseException(pe.getMessage(), pe.getErrorOffset());
226 	}
227 
228 	return aDate;
229     }
230 }