You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

DateUtils.java 9.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. /*
  2. * Copyright 2002-2005 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. * @since Ant 1.5
  33. *
  34. */
  35. public final class DateUtils {
  36. /**
  37. * ISO8601-like pattern for date-time. It does not support timezone.
  38. * <tt>yyyy-MM-ddTHH:mm:ss</tt>
  39. */
  40. public static final String ISO8601_DATETIME_PATTERN
  41. = "yyyy-MM-dd'T'HH:mm:ss";
  42. /**
  43. * ISO8601-like pattern for date. <tt>yyyy-MM-dd</tt>
  44. */
  45. public static final String ISO8601_DATE_PATTERN
  46. = "yyyy-MM-dd";
  47. /**
  48. * ISO8601-like pattern for time. <tt>HH:mm:ss</tt>
  49. */
  50. public static final String ISO8601_TIME_PATTERN
  51. = "HH:mm:ss";
  52. /**
  53. * Format used for SMTP (and probably other) Date headers.
  54. */
  55. public static final DateFormat DATE_HEADER_FORMAT
  56. = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss ", Locale.US);
  57. // code from Magesh moved from DefaultLogger and slightly modified
  58. private static final MessageFormat MINUTE_SECONDS
  59. = new MessageFormat("{0}{1}");
  60. private static final double[] LIMITS = {0, 1, 2};
  61. private static final String[] MINUTES_PART = {"", "1 minute ", "{0,number} minutes "};
  62. private static final String[] SECONDS_PART = {"0 seconds", "1 second", "{1,number} seconds"};
  63. private static final ChoiceFormat MINUTES_FORMAT =
  64. new ChoiceFormat(LIMITS, MINUTES_PART);
  65. private static final ChoiceFormat SECONDS_FORMAT =
  66. new ChoiceFormat(LIMITS, SECONDS_PART);
  67. static {
  68. MINUTE_SECONDS.setFormat(0, MINUTES_FORMAT);
  69. MINUTE_SECONDS.setFormat(1, SECONDS_FORMAT);
  70. }
  71. /** private constructor */
  72. private DateUtils() {
  73. }
  74. /**
  75. * Format a date/time into a specific pattern.
  76. * @param date the date to format expressed in milliseconds.
  77. * @param pattern the pattern to use to format the date.
  78. * @return the formatted date.
  79. */
  80. public static String format(long date, String pattern) {
  81. return format(new Date(date), pattern);
  82. }
  83. /**
  84. * Format a date/time into a specific pattern.
  85. * @param date the date to format expressed in milliseconds.
  86. * @param pattern the pattern to use to format the date.
  87. * @return the formatted date.
  88. */
  89. public static String format(Date date, String pattern) {
  90. DateFormat df = createDateFormat(pattern);
  91. return df.format(date);
  92. }
  93. /**
  94. * Format an elapsed time into a plurialization correct string.
  95. * It is limited only to report elapsed time in minutes and
  96. * seconds and has the following behavior.
  97. * <ul>
  98. * <li>minutes are not displayed when 0. (ie: "45 seconds")</li>
  99. * <li>seconds are always displayed in plural form (ie "0 seconds" or
  100. * "10 seconds") except for 1 (ie "1 second")</li>
  101. * </ul>
  102. * @param millis the elapsed time to report in milliseconds.
  103. * @return the formatted text in minutes/seconds.
  104. */
  105. public static String formatElapsedTime(long millis) {
  106. long seconds = millis / 1000;
  107. long minutes = seconds / 60;
  108. Object[] args = {new Long(minutes), new Long(seconds % 60)};
  109. return MINUTE_SECONDS.format(args);
  110. }
  111. /**
  112. * return a lenient date format set to GMT time zone.
  113. * @param pattern the pattern used for date/time formatting.
  114. * @return the configured format for this pattern.
  115. */
  116. private static DateFormat createDateFormat(String pattern) {
  117. SimpleDateFormat sdf = new SimpleDateFormat(pattern);
  118. TimeZone gmt = TimeZone.getTimeZone("GMT");
  119. sdf.setTimeZone(gmt);
  120. sdf.setLenient(true);
  121. return sdf;
  122. }
  123. /**
  124. * Calculate the phase of the moon for a given date.
  125. *
  126. * <p>Code heavily influenced by hacklib.c in <a
  127. * href="http://www.nethack.org/">Nethack</a></p>
  128. *
  129. * <p>The Algorithm:
  130. *
  131. * <pre>
  132. * moon period = 29.53058 days ~= 30, year = 365.2422 days
  133. *
  134. * days moon phase advances on first day of year compared to preceding year
  135. * = 365.2422 - 12*29.53058 ~= 11
  136. *
  137. * years in Metonic cycle (time until same phases fall on the same days of
  138. * the month) = 18.6 ~= 19
  139. *
  140. * moon phase on first day of year (epact) ~= (11*(year%19) + 18) % 30
  141. * (18 as initial condition for 1900)
  142. *
  143. * current phase in days = first day phase + days elapsed in year
  144. *
  145. * 6 moons ~= 177 days
  146. * 177 ~= 8 reported phases * 22
  147. * + 11/22 for rounding
  148. * </pre>
  149. *
  150. * @param cal the calander.
  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. * @return the current date.
  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. }