View Javadoc

1   /*
2    * Jour - java profiler and monitoring library
3    *
4    * Copyright (C) 2004 Jour team
5    *
6    * This library is free software; you can redistribute it and/or
7    * modify it under the terms of the GNU Library General Public
8    * License as published by the Free Software Foundation; either
9    * version 2 of the License, or (at your option) any later version.
10   *
11   * This library is distributed in the hope that it will be useful,
12   * but WITHOUT ANY WARRANTY; without even the implied warranty of
13   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14   * Library General Public License for more details.
15   *
16   * You should have received a copy of the GNU Library General Public
17   * License along with this library; if not, write to the
18   * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19   * Boston, MA  02111-1307, USA.
20   */
21  package net.sf.jour.util;
22  
23  import java.text.DecimalFormat;
24  import java.text.SimpleDateFormat;
25  import java.util.Date;
26  import java.util.Calendar;
27  import java.util.GregorianCalendar;
28  
29  import org.apache.log4j.Logger;
30  
31  /***
32   * TODO Add docs
33   * Created on 04.12.2004
34   *
35   * Contributing Author(s):
36   *
37   *   Misha Lifschitz <mishalifschitz at users.sourceforge.net> (Inital implementation)
38   *   Vlad Skarzhevskyy <vlads at users.sourceforge.net> (Inital implementation)
39   *
40   * @author vlads
41   * @version $Revision: 1.5 $ ($Author: vlads $) $Date: 2004/12/09 07:26:40 $
42   */
43  public class TimeUtil {
44      
45      protected static final Logger log = Logger.getLogger(TimeUtil.class);
46      
47      public static final boolean debug = true;
48  
49  	public static int string2TimeSec(String str) {
50  		if (str.length() != 8) {
51  			return -1;
52  		}
53  		int h = new Integer(str.substring(0, 2)).intValue();
54  		int m = new Integer(str.substring(3, 5)).intValue();
55  		int s = new Integer(str.substring(6, 8)).intValue();
56  		return s + m * 60 + h * 60 * 60;
57  	}
58  	
59  	public static double string2MTimeSec(String str) {
60  		if (str.length() != 12) {
61  			return string2TimeSec(str);
62  		}
63  		int h = new Integer(str.substring(0, 2)).intValue();
64  		int m = new Integer(str.substring(3, 5)).intValue();
65  		int s = new Integer(str.substring(6, 8)).intValue();
66  		double ms = new Integer(str.substring(9, 12)).intValue();
67  		return s + m * 60 + h * 60 * 60 + (ms / 1000.0);
68  	}
69  
70  	public String timeSec2string(int sec) {
71  		//hh:mm:ss
72  		int h = sec / (60 * 60);
73  		int m = (sec - h * 60 * 60) / 60;
74  		int s = (sec - h * 60 * 60 - m * 60);
75  
76  		DecimalFormat nf = new DecimalFormat("00");
77  
78  		return nf.format(h) + ":" + nf.format(m) + ":" + nf.format(s);
79  	}
80  
81  	public static void trunc(Calendar calendar) {
82  	    dayStart(calendar);
83  	}
84  	
85  	public static void dayStart(Calendar calendar) {
86  		calendar.set(Calendar.SECOND, 0);
87  		calendar.set(Calendar.MINUTE, 0);
88  		calendar.set(Calendar.HOUR_OF_DAY, 0);	    
89  	}
90  	
91  	public static void dayEnd(Calendar calendar) {
92  	    dayStart(calendar);
93  	    calendar.add(Calendar.DATE, 1);
94  	}
95  	
96  	public static double string2TimeStamp(String str) {
97  		if (str == null) {
98  			return 0;
99  		}
100 		String sTime = str.trim();
101 		double sec = string2MTimeSec(sTime);
102 		if (sec != -1) {
103 			Calendar calendar = new GregorianCalendar();
104 			trunc(calendar);
105 			int s = (int)Math.ceil(sec);
106 			calendar.add(Calendar.SECOND, s);
107 			return calendar.getTime().getTime() + (s - sec);
108 		}
109 		try {
110             sec = Double.valueOf(str).doubleValue();
111             if (debug) {
112                 log.debug(str + "->" + timeStamp2dateString(sec));
113             }
114             return sec;
115         } catch (NumberFormatException e) {
116         }
117 
118 		return detectTimeformat(str);
119 	}
120 
121 	static String timeStampFormat = "0000000000000.000";
122 	static DecimalFormat timeStampFormater = new DecimalFormat(timeStampFormat);
123 
124 	public static String timeStamp2string(double timeStamp) {
125 		return timeStampFormater.format(timeStamp);
126 	}
127 
128 	static String timeStampDateFormat = "yyyy-MM-dd HH:mm:ss.SSS";
129 	static SimpleDateFormat timeStampDateFormater = new SimpleDateFormat(timeStampDateFormat);
130 
131 	public static String timeStamp2dateString(double timeStamp) {
132 	    return timeStampDateFormater.format(timeStamp2calendar(timeStamp).getTime());
133 	}
134 	
135 	public static Calendar timeStamp2calendar(double timeStamp) {
136 	    Calendar calendar = new GregorianCalendar();
137 	    calendar.setTime(new Date(new Double(timeStamp).longValue()));
138 		return calendar;
139 	}
140 
141 	public static double calendar2timeStamp(Calendar calendar) {
142 		return calendar.getTime().getTime();
143 	}
144 
145 	private static double detectTimeformat(String str) {
146 		final String[] formats = {
147 		    "yyyy-MM-dd HH:mm:ss.SSS",
148 		    "yyyy-MM-dd HH:mm:ss",
149 		    "yyyy-MM-dd HH:mm",
150 			// We are North America afer all.
151 		    "MM-dd-yyyy HH:mm:ss.SSS",
152 		    "MM-dd-yyyy HH:mm:ss",
153 		    "MM-dd-yyyy HH:mm",
154 		    "MM/dd/yyyy HH:mm:ss.SSS",
155 		    "MM/dd/yyyy HH:mm:ss",
156 		    "MM/dd/yyyy HH:mm",
157 			"MM-dd-yyyy",
158 		    "yyyy-MM-dd",
159 			"MM/dd/yyyy",
160 		};
161 
162         for (int i = 0; i < formats.length; i++) {
163             try {
164                 SimpleDateFormat aFormat = new SimpleDateFormat(formats[i]);
165                 Date dateObj = aFormat.parse(str);
166                 if (!str.equals(aFormat.format(dateObj))) {
167                     continue;
168                 }
169                 if (debug) {
170                     log.debug("date  :" + str);
171                     log.debug("format:" + formats[i] + " " + aFormat.format(dateObj));
172                 }
173                 return dateObj.getTime();
174             } catch (Exception ignore) {
175                 // ignore
176             }
177         }
178         log.warn("undetected date format [" + str + "]");
179 		return 0;
180 	}
181 
182     private static String dateRE = "((//d//d-//d//d-//d//d//d//d)|(//d//d//d//d-//d//d-//d//d)|(//d//d///d//d///d//d//d//d))";
183     private static String intervalOneDayPattern = "^" + dateRE  + "$";
184 
185     private static String tsRE = "//d{12,}";
186 	private static String tsintervalPattern = "^(" + tsRE + ")//s*-//s*(" + tsRE + ")$";
187 	
188 	private static String secRE = "//d//d://d//d://d//d";
189 	private static String intervalPattern = "^(" + secRE + ")//s*-//s*(" + secRE + ")$";
190 	
191 	private static String msecRE = "//d//d://d//d://d//d//.//d//d//d";
192 	private static String intervalPattern1 = "^(" + msecRE + ")//s*-//s*(" + msecRE + ")$";
193 	
194     public static double[] string2TimeInterval(String comp) {
195         if (comp == null) {
196             return null;
197         }
198         comp = comp.trim();
199         String[] fullDay = RegExUtil.match(comp, intervalOneDayPattern);
200         if (fullDay.length >= 1) {
201             double day = string2TimeStamp(fullDay[0]);
202             Calendar dc = timeStamp2calendar(day);
203             double[] rc = new double[2];
204             dayStart(dc);
205             rc[0] = calendar2timeStamp(dc);
206             dayEnd(dc);
207             rc[1] = calendar2timeStamp(dc);
208             return rc;
209         }
210 
211         String[] result = RegExUtil.match(comp, intervalPattern);
212         if (result.length < 2) {
213             result = RegExUtil.match(comp, intervalPattern1);
214         }
215 
216         if (result.length >= 2) {
217             if (debug) {
218                 log.debug(comp + "->["  + result[0] + "]-[" + result[1] + "]" + result.length);
219             }
220             double[] rc = new double[2];
221             rc[0] = string2TimeStamp(result[0]);
222             rc[1] = string2TimeStamp(result[1]);
223             return rc;
224         } else {
225             int idx = comp.indexOf(" - ");
226             if (idx > 0) {
227                 double[] rc = new double[2];
228                 rc[0] = string2TimeStamp(comp.substring(0, idx));
229                 rc[1] = string2TimeStamp(comp.substring(idx + 3));
230                 return rc;
231             }
232             return null;
233         }
234 
235     }
236 }