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 14 kB

11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package org.apache.tools.ant.util;
  19. import java.text.ChoiceFormat;
  20. import java.text.DateFormat;
  21. import java.text.MessageFormat;
  22. import java.text.ParseException;
  23. import java.text.SimpleDateFormat;
  24. import java.util.Calendar;
  25. import java.util.Date;
  26. import java.util.Locale;
  27. import java.util.TimeZone;
  28. import java.util.regex.Matcher;
  29. import java.util.regex.Pattern;
  30. /**
  31. * Helper methods to deal with date/time formatting with a specific
  32. * defined format (<a href="http://www.w3.org/TR/NOTE-datetime">ISO8601</a>)
  33. * or a plurialization correct elapsed time in minutes and seconds.
  34. *
  35. * @since Ant 1.5
  36. *
  37. */
  38. public final class DateUtils {
  39. private static final int ONE_SECOND = 1000;
  40. private static final int ONE_MINUTE = 60;
  41. private static final int ONE_HOUR = 60;
  42. private static final int TEN = 10;
  43. /**
  44. * ISO8601-like pattern for date-time. It does not support timezone.
  45. * <tt>yyyy-MM-ddTHH:mm:ss</tt>
  46. */
  47. public static final String ISO8601_DATETIME_PATTERN
  48. = "yyyy-MM-dd'T'HH:mm:ss";
  49. /**
  50. * ISO8601-like pattern for date. <tt>yyyy-MM-dd</tt>
  51. */
  52. public static final String ISO8601_DATE_PATTERN
  53. = "yyyy-MM-dd";
  54. /**
  55. * ISO8601-like pattern for time. <tt>HH:mm:ss</tt>
  56. */
  57. public static final String ISO8601_TIME_PATTERN
  58. = "HH:mm:ss";
  59. /**
  60. * Format used for SMTP (and probably other) Date headers.
  61. * @deprecated DateFormat is not thread safe, and we cannot guarantee that
  62. * some other code is using the format in parallel.
  63. * Deprecated since ant 1.8
  64. */
  65. public static final DateFormat DATE_HEADER_FORMAT
  66. = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss ", Locale.US);
  67. private static final DateFormat DATE_HEADER_FORMAT_INT
  68. = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss ", Locale.US);
  69. // code from Magesh moved from DefaultLogger and slightly modified
  70. private static final MessageFormat MINUTE_SECONDS
  71. = new MessageFormat("{0}{1}");
  72. private static final double[] LIMITS = {0, 1, 2};
  73. private static final String[] MINUTES_PART = {"", "1 minute ", "{0,number,###############} minutes "};
  74. private static final String[] SECONDS_PART = {"0 seconds", "1 second", "{1,number} seconds"};
  75. private static final ChoiceFormat MINUTES_FORMAT =
  76. new ChoiceFormat(LIMITS, MINUTES_PART);
  77. private static final ChoiceFormat SECONDS_FORMAT =
  78. new ChoiceFormat(LIMITS, SECONDS_PART);
  79. /**
  80. * Provides a thread-local US-style date format. Exactly as used by
  81. * {@code <touch>}, to minute precision:
  82. * {@code SimpleDateFormat("MM/dd/yyyy hh:mm a", Locale.US)}
  83. */
  84. public static final ThreadLocal<DateFormat> EN_US_DATE_FORMAT_MIN =
  85. new ThreadLocal<DateFormat>() {
  86. @Override
  87. protected DateFormat initialValue() {
  88. return new SimpleDateFormat("MM/dd/yyyy hh:mm a", Locale.US);
  89. }
  90. };
  91. /**
  92. * Provides a thread-local US-style date format. Exactly as used by
  93. * {@code <touch>}, to second precision:
  94. * {@code SimpleDateFormat("MM/dd/yyyy hh:mm:ss a", Locale.US)}
  95. */
  96. public static final ThreadLocal<DateFormat> EN_US_DATE_FORMAT_SEC =
  97. new ThreadLocal<DateFormat>() {
  98. @Override
  99. protected DateFormat initialValue() {
  100. return new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a", Locale.US);
  101. }
  102. };
  103. static {
  104. MINUTE_SECONDS.setFormat(0, MINUTES_FORMAT);
  105. MINUTE_SECONDS.setFormat(1, SECONDS_FORMAT);
  106. }
  107. /** private constructor */
  108. private DateUtils() {
  109. }
  110. /**
  111. * Format a date/time into a specific pattern.
  112. * @param date the date to format expressed in milliseconds.
  113. * @param pattern the pattern to use to format the date.
  114. * @return the formatted date.
  115. */
  116. public static String format(long date, String pattern) {
  117. return format(new Date(date), pattern);
  118. }
  119. /**
  120. * Format a date/time into a specific pattern.
  121. * @param date the date to format expressed in milliseconds.
  122. * @param pattern the pattern to use to format the date.
  123. * @return the formatted date.
  124. */
  125. public static String format(Date date, String pattern) {
  126. DateFormat df = createDateFormat(pattern);
  127. return df.format(date);
  128. }
  129. /**
  130. * Format an elapsed time into a plurialization correct string.
  131. * It is limited only to report elapsed time in minutes and
  132. * seconds and has the following behavior.
  133. * <ul>
  134. * <li>minutes are not displayed when 0. (ie: "45 seconds")</li>
  135. * <li>seconds are always displayed in plural form (ie "0 seconds" or
  136. * "10 seconds") except for 1 (ie "1 second")</li>
  137. * </ul>
  138. * @param millis the elapsed time to report in milliseconds.
  139. * @return the formatted text in minutes/seconds.
  140. */
  141. public static String formatElapsedTime(long millis) {
  142. long seconds = millis / ONE_SECOND;
  143. long minutes = seconds / ONE_MINUTE;
  144. Object[] args = {new Long(minutes), new Long(seconds % ONE_MINUTE)};
  145. return MINUTE_SECONDS.format(args);
  146. }
  147. /**
  148. * return a lenient date format set to GMT time zone.
  149. * @param pattern the pattern used for date/time formatting.
  150. * @return the configured format for this pattern.
  151. */
  152. private static DateFormat createDateFormat(String pattern) {
  153. SimpleDateFormat sdf = new SimpleDateFormat(pattern);
  154. TimeZone gmt = TimeZone.getTimeZone("GMT");
  155. sdf.setTimeZone(gmt);
  156. sdf.setLenient(true);
  157. return sdf;
  158. }
  159. /**
  160. * Calculate the phase of the moon for a given date.
  161. *
  162. * <p>Code heavily influenced by hacklib.c in <a
  163. * href="http://www.nethack.org/">Nethack</a></p>
  164. *
  165. * <p>The Algorithm:
  166. *
  167. * <pre>
  168. * moon period = 29.53058 days ~= 30, year = 365.2422 days
  169. *
  170. * days moon phase advances on first day of year compared to preceding year
  171. * = 365.2422 - 12*29.53058 ~= 11
  172. *
  173. * years in Metonic cycle (time until same phases fall on the same days of
  174. * the month) = 18.6 ~= 19
  175. *
  176. * moon phase on first day of year (epact) ~= (11*(year%19) + 18) % 30
  177. * (18 as initial condition for 1900)
  178. *
  179. * current phase in days = first day phase + days elapsed in year
  180. *
  181. * 6 moons ~= 177 days
  182. * 177 ~= 8 reported phases * 22
  183. * + 11/22 for rounding
  184. * </pre>
  185. *
  186. * @param cal the calendar.
  187. *
  188. * @return The phase of the moon as a number between 0 and 7 with
  189. * 0 meaning new moon and 4 meaning full moon.
  190. *
  191. * @since 1.2, Ant 1.5
  192. */
  193. public static int getPhaseOfMoon(Calendar cal) {
  194. // CheckStyle:MagicNumber OFF
  195. int dayOfTheYear = cal.get(Calendar.DAY_OF_YEAR);
  196. int yearInMetonicCycle = ((cal.get(Calendar.YEAR) - 1900) % 19) + 1;
  197. int epact = (11 * yearInMetonicCycle + 18) % 30;
  198. if ((epact == 25 && yearInMetonicCycle > 11) || epact == 24) {
  199. epact++;
  200. }
  201. return (((((dayOfTheYear + epact) * 6) + 11) % 177) / 22) & 7;
  202. // CheckStyle:MagicNumber ON
  203. }
  204. /**
  205. * Returns the current Date in a format suitable for a SMTP date
  206. * header.
  207. * @return the current date.
  208. * @since Ant 1.5.2
  209. */
  210. public static String getDateForHeader() {
  211. Calendar cal = Calendar.getInstance();
  212. TimeZone tz = cal.getTimeZone();
  213. int offset = tz.getOffset(cal.get(Calendar.ERA),
  214. cal.get(Calendar.YEAR),
  215. cal.get(Calendar.MONTH),
  216. cal.get(Calendar.DAY_OF_MONTH),
  217. cal.get(Calendar.DAY_OF_WEEK),
  218. cal.get(Calendar.MILLISECOND));
  219. StringBuffer tzMarker = new StringBuffer(offset < 0 ? "-" : "+");
  220. offset = Math.abs(offset);
  221. int hours = offset / (ONE_HOUR * ONE_MINUTE * ONE_SECOND);
  222. int minutes = offset / (ONE_MINUTE * ONE_SECOND) - ONE_HOUR * hours;
  223. if (hours < TEN) {
  224. tzMarker.append("0");
  225. }
  226. tzMarker.append(hours);
  227. if (minutes < TEN) {
  228. tzMarker.append("0");
  229. }
  230. tzMarker.append(minutes);
  231. synchronized (DATE_HEADER_FORMAT_INT) {
  232. return DATE_HEADER_FORMAT_INT.format(cal.getTime()) + tzMarker.toString();
  233. }
  234. }
  235. /**
  236. * Parses the string in a format suitable for a SMTP date header.
  237. *
  238. * @param datestr string to be parsed
  239. *
  240. * @return a java.util.Date object as parsed by the format.
  241. * @exception ParseException if the supplied string cannot be parsed by
  242. * this pattern.
  243. * @since Ant 1.8.0
  244. */
  245. public static Date parseDateFromHeader(String datestr) throws ParseException {
  246. synchronized (DATE_HEADER_FORMAT_INT) {
  247. return DATE_HEADER_FORMAT_INT.parse(datestr);
  248. }
  249. }
  250. /**
  251. * Parse a string as a datetime using the ISO8601_DATETIME format which is
  252. * <code>yyyy-MM-dd'T'HH:mm:ss</code>
  253. *
  254. * @param datestr string to be parsed
  255. *
  256. * @return a java.util.Date object as parsed by the format.
  257. * @exception ParseException if the supplied string cannot be parsed by
  258. * this pattern.
  259. * @since Ant 1.6
  260. */
  261. public static Date parseIso8601DateTime(String datestr)
  262. throws ParseException {
  263. return new SimpleDateFormat(ISO8601_DATETIME_PATTERN).parse(datestr);
  264. }
  265. /**
  266. * Parse a string as a date using the ISO8601_DATE format which is
  267. * <code>yyyy-MM-dd</code>
  268. *
  269. * @param datestr string to be parsed
  270. *
  271. * @return a java.util.Date object as parsed by the format.
  272. * @exception ParseException if the supplied string cannot be parsed by
  273. * this pattern.
  274. * @since Ant 1.6
  275. */
  276. public static Date parseIso8601Date(String datestr) throws ParseException {
  277. return new SimpleDateFormat(ISO8601_DATE_PATTERN).parse(datestr);
  278. }
  279. /**
  280. * Parse a string as a date using the either the ISO8601_DATETIME
  281. * or ISO8601_DATE formats.
  282. *
  283. * @param datestr string to be parsed
  284. *
  285. * @return a java.util.Date object as parsed by the formats.
  286. * @exception ParseException if the supplied string cannot be parsed by
  287. * either of these patterns.
  288. * @since Ant 1.6
  289. */
  290. public static Date parseIso8601DateTimeOrDate(String datestr)
  291. throws ParseException {
  292. try {
  293. return parseIso8601DateTime(datestr);
  294. } catch (ParseException px) {
  295. return parseIso8601Date(datestr);
  296. }
  297. }
  298. final private static ThreadLocal<DateFormat> iso8601WithTimeZone =
  299. new ThreadLocal<DateFormat>() {
  300. @Override protected DateFormat initialValue() {
  301. // An arbitrary easy-to-read format to normalize to.
  302. return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS Z");
  303. }
  304. };
  305. final private static Pattern iso8601normalizer = Pattern.compile(
  306. "^(\\d{4,}-\\d{2}-\\d{2})[Tt ]" + // yyyy-MM-dd
  307. "(\\d{2}:\\d{2}(:\\d{2}(\\.\\d{3})?)?) ?" + // HH:mm:ss.SSS
  308. "(?:Z|([+-]\\d{2})(?::?(\\d{2}))?)?$"); // Z
  309. /**
  310. * Parse a lenient ISO 8601, ms since epoch, or {@code <touch>}-style date.
  311. * That is:
  312. * <ul>
  313. * <li>Milliseconds since 1970-01-01 00:00</li>
  314. * <li><code>YYYY-MM-DD{T| }HH:MM[:SS[.SSS]][ ][±ZZ[[:]ZZ]]</code></li>
  315. * <li><code>MM/DD/YYYY HH:MM[:SS] {AM|PM}</code></li></ul>
  316. * where {a|b} indicates that you must choose one of a or b, and [c]
  317. * indicates that you may use or omit c. ±ZZZZ is the timezone offset, and
  318. * may be literally "Z" to mean GMT.
  319. */
  320. public static Date parseLenientDateTime(String dateStr) throws ParseException {
  321. try {
  322. return new Date(Long.parseLong(dateStr));
  323. } catch (NumberFormatException nfe) {}
  324. try {
  325. return EN_US_DATE_FORMAT_MIN.get().parse(dateStr);
  326. } catch (ParseException pe) {}
  327. try {
  328. return EN_US_DATE_FORMAT_SEC.get().parse(dateStr);
  329. } catch (ParseException pe) {}
  330. Matcher m = iso8601normalizer.matcher(dateStr);
  331. if (!m.find()) throw new ParseException(dateStr, 0);
  332. String normISO = m.group(1) + " "
  333. + (m.group(3) == null ? m.group(2) + ":00" : m.group(2))
  334. + (m.group(4) == null ? ".000 " : " ")
  335. + (m.group(5) == null ? "+00" : m.group(5))
  336. + (m.group(6) == null ? "00" : m.group(6));
  337. return iso8601WithTimeZone.get().parse(normISO);
  338. }
  339. }