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.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. /*
  2. * The Apache Software License, Version 1.1
  3. *
  4. * Copyright (c) 2002 The Apache Software Foundation. All rights
  5. * reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions
  9. * are met:
  10. *
  11. * 1. Redistributions of source code must retain the above copyright
  12. * notice, this list of conditions and the following disclaimer.
  13. *
  14. * 2. Redistributions in binary form must reproduce the above copyright
  15. * notice, this list of conditions and the following disclaimer in
  16. * the documentation and/or other materials provided with the
  17. * distribution.
  18. *
  19. * 3. The end-user documentation included with the redistribution, if
  20. * any, must include the following acknowlegement:
  21. * "This product includes software developed by the
  22. * Apache Software Foundation (http://www.apache.org/)."
  23. * Alternately, this acknowlegement may appear in the software itself,
  24. * if and wherever such third-party acknowlegements normally appear.
  25. *
  26. * 4. The names "Ant" and "Apache Software
  27. * Foundation" must not be used to endorse or promote products derived
  28. * from this software without prior written permission. For written
  29. * permission, please contact apache@apache.org.
  30. *
  31. * 5. Products derived from this software may not be called "Apache"
  32. * nor may "Apache" appear in their names without prior written
  33. * permission of the Apache Group.
  34. *
  35. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  36. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  37. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  38. * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
  39. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  40. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  41. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  42. * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  43. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  44. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  45. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  46. * SUCH DAMAGE.
  47. * ====================================================================
  48. *
  49. * This software consists of voluntary contributions made by many
  50. * individuals on behalf of the Apache Software Foundation. For more
  51. * information on the Apache Software Foundation, please see
  52. * <http://www.apache.org/>.
  53. */
  54. package org.apache.tools.ant.util;
  55. import java.text.ChoiceFormat;
  56. import java.text.DateFormat;
  57. import java.text.MessageFormat;
  58. import java.text.SimpleDateFormat;
  59. import java.util.Calendar;
  60. import java.util.Date;
  61. import java.util.Locale;
  62. import java.util.TimeZone;
  63. /**
  64. * Helper methods to deal with date/time formatting with a specific
  65. * defined format (<a href="http://www.w3.org/TR/NOTE-datetime">ISO8601</a>)
  66. * or a plurialization correct elapsed time in minutes and seconds.
  67. *
  68. * @author <a href="mailto:sbailliez@apache.org">Stephane Bailliez</a>
  69. * @author Stefan Bodewig
  70. *
  71. * @since Ant 1.5
  72. *
  73. * @version $Revision$
  74. */
  75. public final class DateUtils {
  76. /**
  77. * ISO8601-like pattern for date-time. It does not support timezone.
  78. * <tt>yyyy-MM-ddTHH:mm:ss</tt>
  79. */
  80. public static final String ISO8601_DATETIME_PATTERN
  81. = "yyyy-MM-dd'T'HH:mm:ss";
  82. /**
  83. * ISO8601-like pattern for date. <tt>yyyy-MM-dd</tt>
  84. */
  85. public static final String ISO8601_DATE_PATTERN
  86. = "yyyy-MM-dd";
  87. /**
  88. * ISO8601-like pattern for time. <tt>HH:mm:ss</tt>
  89. */
  90. public static final String ISO8601_TIME_PATTERN
  91. = "HH:mm:ss";
  92. /**
  93. * Format used for SMTP (and probably other) Date headers.
  94. */
  95. public static final DateFormat DATE_HEADER_FORMAT
  96. = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss ", Locale.US);
  97. // code from Magesh moved from DefaultLogger and slightly modified
  98. private static final MessageFormat MINUTE_SECONDS
  99. = new MessageFormat("{0}{1}");
  100. private static final double[] LIMITS = {0, 1, 2};
  101. private static final String[] MINUTES_PART =
  102. {"", "1 minute ", "{0,number} minutes "};
  103. private static final String[] SECONDS_PART =
  104. {"0 seconds", "1 second", "{1,number} seconds"};
  105. private static final ChoiceFormat MINUTES_FORMAT =
  106. new ChoiceFormat(LIMITS, MINUTES_PART);
  107. private static final ChoiceFormat SECONDS_FORMAT =
  108. new ChoiceFormat(LIMITS, SECONDS_PART);
  109. static {
  110. MINUTE_SECONDS.setFormat(0, MINUTES_FORMAT);
  111. MINUTE_SECONDS.setFormat(1, SECONDS_FORMAT);
  112. }
  113. /** private constructor */
  114. private DateUtils() {
  115. }
  116. /**
  117. * Format a date/time into a specific pattern.
  118. * @param date the date to format expressed in milliseconds.
  119. * @param pattern the pattern to use to format the date.
  120. * @return the formatted date.
  121. */
  122. public static String format(long date, String pattern) {
  123. return format(new Date(date), pattern);
  124. }
  125. /**
  126. * Format a date/time into a specific pattern.
  127. * @param date the date to format expressed in milliseconds.
  128. * @param pattern the pattern to use to format the date.
  129. * @return the formatted date.
  130. */
  131. public static String format(Date date, String pattern) {
  132. DateFormat df = createDateFormat(pattern);
  133. return df.format(date);
  134. }
  135. /**
  136. * Format an elapsed time into a plurialization correct string.
  137. * It is limited only to report elapsed time in minutes and
  138. * seconds and has the following behavior.
  139. * <ul>
  140. * <li>minutes are not displayed when 0. (ie: "45 seconds")</li>
  141. * <li>seconds are always displayed in plural form (ie "0 seconds" or
  142. * "10 seconds") except for 1 (ie "1 second")</li>
  143. * </ul>
  144. * @param time the elapsed time to report in milliseconds.
  145. * @return the formatted text in minutes/seconds.
  146. */
  147. public static String formatElapsedTime(long millis) {
  148. long seconds = millis / 1000;
  149. long minutes = seconds / 60;
  150. Object[] args = {new Long(minutes), new Long(seconds % 60)};
  151. return MINUTE_SECONDS.format(args);
  152. }
  153. /**
  154. * return a lenient date format set to GMT time zone.
  155. * @param pattern the pattern used for date/time formatting.
  156. * @return the configured format for this pattern.
  157. */
  158. private static DateFormat createDateFormat(String pattern) {
  159. SimpleDateFormat sdf = new SimpleDateFormat(pattern);
  160. TimeZone gmt = TimeZone.getTimeZone("GMT");
  161. sdf.setTimeZone(gmt);
  162. sdf.setLenient(true);
  163. return sdf;
  164. }
  165. /**
  166. * Calculate the phase of the moon for a given date.
  167. *
  168. * <p>Code heavily influenced by hacklib.c in <a
  169. * href="http://www.nethack.org/">Nethack</a></p>
  170. *
  171. * <p>The Algorithm:
  172. *
  173. * <pre>
  174. * moon period = 29.53058 days ~= 30, year = 365.2422 days
  175. *
  176. * days moon phase advances on first day of year compared to preceding year
  177. * = 365.2422 - 12*29.53058 ~= 11
  178. *
  179. * years in Metonic cycle (time until same phases fall on the same days of
  180. * the month) = 18.6 ~= 19
  181. *
  182. * moon phase on first day of year (epact) ~= (11*(year%19) + 18) % 30
  183. * (18 as initial condition for 1900)
  184. *
  185. * current phase in days = first day phase + days elapsed in year
  186. *
  187. * 6 moons ~= 177 days
  188. * 177 ~= 8 reported phases * 22
  189. * + 11/22 for rounding
  190. * </pre>
  191. *
  192. * @return The phase of the moon as a number between 0 and 7 with
  193. * 0 meaning new moon and 4 meaning full moon.
  194. *
  195. * @since 1.2, Ant 1.5
  196. */
  197. public static int getPhaseOfMoon(Calendar cal) {
  198. int dayOfTheYear = cal.get(Calendar.DAY_OF_YEAR);
  199. int yearInMetonicCycle = ((cal.get(Calendar.YEAR) - 1900) % 19) + 1;
  200. int epact = (11 * yearInMetonicCycle + 18) % 30;
  201. if ((epact == 25 && yearInMetonicCycle > 11) || epact == 24) {
  202. epact++;
  203. }
  204. return (((((dayOfTheYear + epact) * 6) + 11) % 177) / 22) & 7;
  205. }
  206. /**
  207. * Returns the current Date in a format suitable for a SMTP date
  208. * header.
  209. *
  210. * @since Ant 1.5.2
  211. */
  212. public static String getDateForHeader() {
  213. Calendar cal = Calendar.getInstance();
  214. TimeZone tz = cal.getTimeZone();
  215. int offset = tz.getOffset(cal.get(Calendar.ERA),
  216. cal.get(Calendar.YEAR),
  217. cal.get(Calendar.MONTH),
  218. cal.get(Calendar.DAY_OF_MONTH),
  219. cal.get(Calendar.DAY_OF_WEEK),
  220. cal.get(Calendar.MILLISECOND));
  221. StringBuffer tzMarker = new StringBuffer(offset < 0 ? "-" : "+");
  222. offset = Math.abs(offset);
  223. int hours = offset / (60 * 60 * 1000);
  224. int minutes = offset / (60 * 1000) - 60 * hours;
  225. if (hours < 10) {
  226. tzMarker.append("0");
  227. }
  228. tzMarker.append(hours);
  229. if (minutes < 10) {
  230. tzMarker.append("0");
  231. }
  232. tzMarker.append(minutes);
  233. return DATE_HEADER_FORMAT.format(cal.getTime()) + tzMarker.toString();
  234. }
  235. }