001: /*
002: * Licensed to the Apache Software Foundation (ASF) under one or more
003: * contributor license agreements. See the NOTICE file distributed with
004: * this work for additional information regarding copyright ownership.
005: * The ASF licenses this file to You under the Apache License, Version 2.0
006: * (the "License"); you may not use this file except in compliance with
007: * the License. You may obtain a copy of the License at
008: *
009: * http://www.apache.org/licenses/LICENSE-2.0
010: *
011: * Unless required by applicable law or agreed to in writing, software
012: * distributed under the License is distributed on an "AS IS" BASIS,
013: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014: * See the License for the specific language governing permissions and
015: * limitations under the License.
016: *
017: */
018: package org.apache.tools.ant.util;
019:
020: import java.text.ChoiceFormat;
021: import java.text.DateFormat;
022: import java.text.MessageFormat;
023: import java.text.ParseException;
024: import java.text.SimpleDateFormat;
025: import java.util.Calendar;
026: import java.util.Date;
027: import java.util.Locale;
028: import java.util.TimeZone;
029:
030: /**
031: * Helper methods to deal with date/time formatting with a specific
032: * defined format (<a href="http://www.w3.org/TR/NOTE-datetime">ISO8601</a>)
033: * or a plurialization correct elapsed time in minutes and seconds.
034: *
035: * @since Ant 1.5
036: *
037: */
038: public final class DateUtils {
039:
040: /**
041: * ISO8601-like pattern for date-time. It does not support timezone.
042: * <tt>yyyy-MM-ddTHH:mm:ss</tt>
043: */
044: public static final String ISO8601_DATETIME_PATTERN = "yyyy-MM-dd'T'HH:mm:ss";
045:
046: /**
047: * ISO8601-like pattern for date. <tt>yyyy-MM-dd</tt>
048: */
049: public static final String ISO8601_DATE_PATTERN = "yyyy-MM-dd";
050:
051: /**
052: * ISO8601-like pattern for time. <tt>HH:mm:ss</tt>
053: */
054: public static final String ISO8601_TIME_PATTERN = "HH:mm:ss";
055:
056: /**
057: * Format used for SMTP (and probably other) Date headers.
058: */
059: public static final DateFormat DATE_HEADER_FORMAT = new SimpleDateFormat(
060: "EEE, dd MMM yyyy HH:mm:ss ", Locale.US);
061:
062: // code from Magesh moved from DefaultLogger and slightly modified
063: private static final MessageFormat MINUTE_SECONDS = new MessageFormat(
064: "{0}{1}");
065:
066: private static final double[] LIMITS = { 0, 1, 2 };
067:
068: private static final String[] MINUTES_PART = { "", "1 minute ",
069: "{0,number} minutes " };
070:
071: private static final String[] SECONDS_PART = { "0 seconds",
072: "1 second", "{1,number} seconds" };
073:
074: private static final ChoiceFormat MINUTES_FORMAT = new ChoiceFormat(
075: LIMITS, MINUTES_PART);
076:
077: private static final ChoiceFormat SECONDS_FORMAT = new ChoiceFormat(
078: LIMITS, SECONDS_PART);
079:
080: static {
081: MINUTE_SECONDS.setFormat(0, MINUTES_FORMAT);
082: MINUTE_SECONDS.setFormat(1, SECONDS_FORMAT);
083: }
084:
085: /** private constructor */
086: private DateUtils() {
087: }
088:
089: /**
090: * Format a date/time into a specific pattern.
091: * @param date the date to format expressed in milliseconds.
092: * @param pattern the pattern to use to format the date.
093: * @return the formatted date.
094: */
095: public static String format(long date, String pattern) {
096: return format(new Date(date), pattern);
097: }
098:
099: /**
100: * Format a date/time into a specific pattern.
101: * @param date the date to format expressed in milliseconds.
102: * @param pattern the pattern to use to format the date.
103: * @return the formatted date.
104: */
105: public static String format(Date date, String pattern) {
106: DateFormat df = createDateFormat(pattern);
107: return df.format(date);
108: }
109:
110: /**
111: * Format an elapsed time into a plurialization correct string.
112: * It is limited only to report elapsed time in minutes and
113: * seconds and has the following behavior.
114: * <ul>
115: * <li>minutes are not displayed when 0. (ie: "45 seconds")</li>
116: * <li>seconds are always displayed in plural form (ie "0 seconds" or
117: * "10 seconds") except for 1 (ie "1 second")</li>
118: * </ul>
119: * @param millis the elapsed time to report in milliseconds.
120: * @return the formatted text in minutes/seconds.
121: */
122: public static String formatElapsedTime(long millis) {
123: long seconds = millis / 1000;
124: long minutes = seconds / 60;
125: Object[] args = { new Long(minutes), new Long(seconds % 60) };
126: return MINUTE_SECONDS.format(args);
127: }
128:
129: /**
130: * return a lenient date format set to GMT time zone.
131: * @param pattern the pattern used for date/time formatting.
132: * @return the configured format for this pattern.
133: */
134: private static DateFormat createDateFormat(String pattern) {
135: SimpleDateFormat sdf = new SimpleDateFormat(pattern);
136: TimeZone gmt = TimeZone.getTimeZone("GMT");
137: sdf.setTimeZone(gmt);
138: sdf.setLenient(true);
139: return sdf;
140: }
141:
142: /**
143: * Calculate the phase of the moon for a given date.
144: *
145: * <p>Code heavily influenced by hacklib.c in <a
146: * href="http://www.nethack.org/">Nethack</a></p>
147: *
148: * <p>The Algorithm:
149: *
150: * <pre>
151: * moon period = 29.53058 days ~= 30, year = 365.2422 days
152: *
153: * days moon phase advances on first day of year compared to preceding year
154: * = 365.2422 - 12*29.53058 ~= 11
155: *
156: * years in Metonic cycle (time until same phases fall on the same days of
157: * the month) = 18.6 ~= 19
158: *
159: * moon phase on first day of year (epact) ~= (11*(year%19) + 18) % 30
160: * (18 as initial condition for 1900)
161: *
162: * current phase in days = first day phase + days elapsed in year
163: *
164: * 6 moons ~= 177 days
165: * 177 ~= 8 reported phases * 22
166: * + 11/22 for rounding
167: * </pre>
168: *
169: * @param cal the calander.
170: *
171: * @return The phase of the moon as a number between 0 and 7 with
172: * 0 meaning new moon and 4 meaning full moon.
173: *
174: * @since 1.2, Ant 1.5
175: */
176: public static int getPhaseOfMoon(Calendar cal) {
177: int dayOfTheYear = cal.get(Calendar.DAY_OF_YEAR);
178: int yearInMetonicCycle = ((cal.get(Calendar.YEAR) - 1900) % 19) + 1;
179: int epact = (11 * yearInMetonicCycle + 18) % 30;
180: if ((epact == 25 && yearInMetonicCycle > 11) || epact == 24) {
181: epact++;
182: }
183: return (((((dayOfTheYear + epact) * 6) + 11) % 177) / 22) & 7;
184: }
185:
186: /**
187: * Returns the current Date in a format suitable for a SMTP date
188: * header.
189: * @return the current date.
190: * @since Ant 1.5.2
191: */
192: public static String getDateForHeader() {
193: Calendar cal = Calendar.getInstance();
194: TimeZone tz = cal.getTimeZone();
195: int offset = tz.getOffset(cal.get(Calendar.ERA), cal
196: .get(Calendar.YEAR), cal.get(Calendar.MONTH), cal
197: .get(Calendar.DAY_OF_MONTH), cal
198: .get(Calendar.DAY_OF_WEEK), cal
199: .get(Calendar.MILLISECOND));
200: StringBuffer tzMarker = new StringBuffer(offset < 0 ? "-" : "+");
201: offset = Math.abs(offset);
202: int hours = offset / (60 * 60 * 1000);
203: int minutes = offset / (60 * 1000) - 60 * hours;
204: if (hours < 10) {
205: tzMarker.append("0");
206: }
207: tzMarker.append(hours);
208: if (minutes < 10) {
209: tzMarker.append("0");
210: }
211: tzMarker.append(minutes);
212: return DATE_HEADER_FORMAT.format(cal.getTime())
213: + tzMarker.toString();
214: }
215:
216: /**
217: * Parse a string as a datetime using the ISO8601_DATETIME format which is
218: * <code>yyyy-MM-dd'T'HH:mm:ss</code>
219: *
220: * @param datestr string to be parsed
221: *
222: * @return a java.util.Date object as parsed by the format.
223: * @exception ParseException if the supplied string cannot be parsed by
224: * this pattern.
225: * @since Ant 1.6
226: */
227: public static Date parseIso8601DateTime(String datestr)
228: throws ParseException {
229: return new SimpleDateFormat(ISO8601_DATETIME_PATTERN)
230: .parse(datestr);
231: }
232:
233: /**
234: * Parse a string as a date using the ISO8601_DATE format which is
235: * <code>yyyy-MM-dd</code>
236: *
237: * @param datestr string to be parsed
238: *
239: * @return a java.util.Date object as parsed by the format.
240: * @exception ParseException if the supplied string cannot be parsed by
241: * this pattern.
242: * @since Ant 1.6
243: */
244: public static Date parseIso8601Date(String datestr)
245: throws ParseException {
246: return new SimpleDateFormat(ISO8601_DATE_PATTERN)
247: .parse(datestr);
248: }
249:
250: /**
251: * Parse a string as a date using the either the ISO8601_DATETIME
252: * or ISO8601_DATE formats.
253: *
254: * @param datestr string to be parsed
255: *
256: * @return a java.util.Date object as parsed by the formats.
257: * @exception ParseException if the supplied string cannot be parsed by
258: * either of these patterns.
259: * @since Ant 1.6
260: */
261: public static Date parseIso8601DateTimeOrDate(String datestr)
262: throws ParseException {
263: try {
264: return parseIso8601DateTime(datestr);
265: } catch (ParseException px) {
266: return parseIso8601Date(datestr);
267: }
268: }
269: }
|