1. /*
  2. * Copyright 2002-2004 The Apache Software Foundation
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *
  16. */
  17. package org.apache.tools.ant.util;
  18. import java.text.ChoiceFormat;
  19. import java.text.DateFormat;
  20. import java.text.MessageFormat;
  21. import java.text.ParseException;
  22. import java.text.SimpleDateFormat;
  23. import java.util.Calendar;
  24. import java.util.Date;
  25. import java.util.Locale;
  26. import java.util.TimeZone;
  27. /**
  28. * Helper methods to deal with date/time formatting with a specific
  29. * defined format (<a href="http://www.w3.org/TR/NOTE-datetime">ISO8601</a>)
  30. * or a plurialization correct elapsed time in minutes and seconds.
  31. *
  32. *
  33. * @since Ant 1.5
  34. *
  35. * @version $Revision: 1.11.2.4 $
  36. */
  37. public final class DateUtils {
  38. /**
  39. * ISO8601-like pattern for date-time. It does not support timezone.
  40. * <tt>yyyy-MM-ddTHH:mm:ss</tt>
  41. */
  42. public static final String ISO8601_DATETIME_PATTERN
  43. = "yyyy-MM-dd'T'HH:mm:ss";
  44. /**
  45. * ISO8601-like pattern for date. <tt>yyyy-MM-dd</tt>
  46. */
  47. public static final String ISO8601_DATE_PATTERN
  48. = "yyyy-MM-dd";
  49. /**
  50. * ISO8601-like pattern for time. <tt>HH:mm:ss</tt>
  51. */
  52. public static final String ISO8601_TIME_PATTERN
  53. = "HH:mm:ss";
  54. /**
  55. * Format used for SMTP (and probably other) Date headers.
  56. */
  57. public static final DateFormat DATE_HEADER_FORMAT
  58. = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss ", Locale.US);
  59. // code from Magesh moved from DefaultLogger and slightly modified
  60. private static final MessageFormat MINUTE_SECONDS
  61. = new MessageFormat("{0}{1}");
  62. private static final double[] LIMITS = {0, 1, 2};
  63. private static final String[] MINUTES_PART = {"", "1 minute ", "{0,number} minutes "};
  64. private static final String[] SECONDS_PART = {"0 seconds", "1 second", "{1,number} seconds"};
  65. private static final ChoiceFormat MINUTES_FORMAT =
  66. new ChoiceFormat(LIMITS, MINUTES_PART);
  67. private static final ChoiceFormat SECONDS_FORMAT =
  68. new ChoiceFormat(LIMITS, SECONDS_PART);
  69. static {
  70. MINUTE_SECONDS.setFormat(0, MINUTES_FORMAT);
  71. MINUTE_SECONDS.setFormat(1, SECONDS_FORMAT);
  72. }
  73. /** private constructor */
  74. private DateUtils() {
  75. }
  76. /**
  77. * Format a date/time into a specific pattern.
  78. * @param date the date to format expressed in milliseconds.
  79. * @param pattern the pattern to use to format the date.
  80. * @return the formatted date.
  81. */
  82. public static String format(long date, String pattern) {
  83. return format(new Date(date), pattern);
  84. }
  85. /**
  86. * Format a date/time into a specific pattern.
  87. * @param date the date to format expressed in milliseconds.
  88. * @param pattern the pattern to use to format the date.
  89. * @return the formatted date.
  90. */
  91. public static String format(Date date, String pattern) {
  92. DateFormat df = createDateFormat(pattern);
  93. return df.format(date);
  94. }
  95. /**
  96. * Format an elapsed time into a plurialization correct string.
  97. * It is limited only to report elapsed time in minutes and
  98. * seconds and has the following behavior.
  99. * <ul>
  100. * <li>minutes are not displayed when 0. (ie: "45 seconds")</li>
  101. * <li>seconds are always displayed in plural form (ie "0 seconds" or
  102. * "10 seconds") except for 1 (ie "1 second")</li>
  103. * </ul>
  104. * @param millis the elapsed time to report in milliseconds.
  105. * @return the formatted text in minutes/seconds.
  106. */
  107. public static String formatElapsedTime(long millis) {
  108. long seconds = millis / 1000;
  109. long minutes = seconds / 60;
  110. Object[] args = {new Long(minutes), new Long(seconds % 60)};
  111. return MINUTE_SECONDS.format(args);
  112. }
  113. /**
  114. * return a lenient date format set to GMT time zone.
  115. * @param pattern the pattern used for date/time formatting.
  116. * @return the configured format for this pattern.
  117. */
  118. private static DateFormat createDateFormat(String pattern) {
  119. SimpleDateFormat sdf = new SimpleDateFormat(pattern);
  120. TimeZone gmt = TimeZone.getTimeZone("GMT");
  121. sdf.setTimeZone(gmt);
  122. sdf.setLenient(true);
  123. return sdf;
  124. }
  125. /**
  126. * Calculate the phase of the moon for a given date.
  127. *
  128. * <p>Code heavily influenced by hacklib.c in <a
  129. * href="http://www.nethack.org/">Nethack</a></p>
  130. *
  131. * <p>The Algorithm:
  132. *
  133. * <pre>
  134. * moon period = 29.53058 days ~= 30, year = 365.2422 days
  135. *
  136. * days moon phase advances on first day of year compared to preceding year
  137. * = 365.2422 - 12*29.53058 ~= 11
  138. *
  139. * years in Metonic cycle (time until same phases fall on the same days of
  140. * the month) = 18.6 ~= 19
  141. *
  142. * moon phase on first day of year (epact) ~= (11*(year%19) + 18) % 30
  143. * (18 as initial condition for 1900)
  144. *
  145. * current phase in days = first day phase + days elapsed in year
  146. *
  147. * 6 moons ~= 177 days
  148. * 177 ~= 8 reported phases * 22
  149. * + 11/22 for rounding
  150. * </pre>
  151. *
  152. * @return The phase of the moon as a number between 0 and 7 with
  153. * 0 meaning new moon and 4 meaning full moon.
  154. *
  155. * @since 1.2, Ant 1.5
  156. */
  157. public static int getPhaseOfMoon(Calendar cal) {
  158. int dayOfTheYear = cal.get(Calendar.DAY_OF_YEAR);
  159. int yearInMetonicCycle = ((cal.get(Calendar.YEAR) - 1900) % 19) + 1;
  160. int epact = (11 * yearInMetonicCycle + 18) % 30;
  161. if ((epact == 25 && yearInMetonicCycle > 11) || epact == 24) {
  162. epact++;
  163. }
  164. return (((((dayOfTheYear + epact) * 6) + 11) % 177) / 22) & 7;
  165. }
  166. /**
  167. * Returns the current Date in a format suitable for a SMTP date
  168. * header.
  169. *
  170. * @since Ant 1.5.2
  171. */
  172. public static String getDateForHeader() {
  173. Calendar cal = Calendar.getInstance();
  174. TimeZone tz = cal.getTimeZone();
  175. int offset = tz.getOffset(cal.get(Calendar.ERA),
  176. cal.get(Calendar.YEAR),
  177. cal.get(Calendar.MONTH),
  178. cal.get(Calendar.DAY_OF_MONTH),
  179. cal.get(Calendar.DAY_OF_WEEK),
  180. cal.get(Calendar.MILLISECOND));
  181. StringBuffer tzMarker = new StringBuffer(offset < 0 ? "-" : "+");
  182. offset = Math.abs(offset);
  183. int hours = offset / (60 * 60 * 1000);
  184. int minutes = offset / (60 * 1000) - 60 * hours;
  185. if (hours < 10) {
  186. tzMarker.append("0");
  187. }
  188. tzMarker.append(hours);
  189. if (minutes < 10) {
  190. tzMarker.append("0");
  191. }
  192. tzMarker.append(minutes);
  193. return DATE_HEADER_FORMAT.format(cal.getTime()) + tzMarker.toString();
  194. }
  195. /**
  196. * Parse a string as a datetime using the ISO8601_DATETIME format which is
  197. * <code>yyyy-MM-dd'T'HH:mm:ss</code>
  198. *
  199. * @param datestr string to be parsed
  200. *
  201. * @return a java.util.Date object as parsed by the format.
  202. * @exception ParseException if the supplied string cannot be parsed by
  203. * this pattern.
  204. * @since Ant 1.6
  205. */
  206. public static Date parseIso8601DateTime(String datestr)
  207. throws ParseException {
  208. return new SimpleDateFormat(ISO8601_DATETIME_PATTERN).parse(datestr);
  209. }
  210. /**
  211. * Parse a string as a date using the ISO8601_DATE format which is
  212. * <code>yyyy-MM-dd</code>
  213. *
  214. * @param datestr string to be parsed
  215. *
  216. * @return a java.util.Date object as parsed by the format.
  217. * @exception ParseException if the supplied string cannot be parsed by
  218. * this pattern.
  219. * @since Ant 1.6
  220. */
  221. public static Date parseIso8601Date(String datestr) throws ParseException {
  222. return new SimpleDateFormat(ISO8601_DATE_PATTERN).parse(datestr);
  223. }
  224. /**
  225. * Parse a string as a date using the either the ISO8601_DATETIME
  226. * or ISO8601_DATE formats.
  227. *
  228. * @param datestr string to be parsed
  229. *
  230. * @return a java.util.Date object as parsed by the formats.
  231. * @exception ParseException if the supplied string cannot be parsed by
  232. * either of these patterns.
  233. * @since Ant 1.6
  234. */
  235. public static Date parseIso8601DateTimeOrDate(String datestr)
  236. throws ParseException {
  237. try {
  238. return parseIso8601DateTime(datestr);
  239. } catch (ParseException px) {
  240. return parseIso8601Date(datestr);
  241. }
  242. }
  243. }