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

DateUtil.java 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  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. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.ss.usermodel;
  16. import java.util.Calendar;
  17. import java.util.Date;
  18. import java.util.GregorianCalendar;
  19. import java.util.TimeZone;
  20. import java.util.regex.Pattern;
  21. /**
  22. * Contains methods for dealing with Excel dates.
  23. *
  24. * @author Michael Harhen
  25. * @author Glen Stampoultzis (glens at apache.org)
  26. * @author Dan Sherman (dsherman at isisph.com)
  27. * @author Hack Kampbjorn (hak at 2mba.dk)
  28. * @author Alex Jacoby (ajacoby at gmail.com)
  29. * @author Pavel Krupets (pkrupets at palmtreebusiness dot com)
  30. * @author Thies Wellpott
  31. */
  32. public class DateUtil {
  33. protected DateUtil() {
  34. // no instances of this class
  35. }
  36. public static final int SECONDS_PER_MINUTE = 60;
  37. public static final int MINUTES_PER_HOUR = 60;
  38. public static final int HOURS_PER_DAY = 24;
  39. public static final int SECONDS_PER_DAY = (HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE);
  40. private static final int BAD_DATE = -1; // used to specify that date is invalid
  41. public static final long DAY_MILLISECONDS = SECONDS_PER_DAY * 1000L;
  42. private static final Pattern TIME_SEPARATOR_PATTERN = Pattern.compile(":");
  43. /**
  44. * The following patterns are used in {@link #isADateFormat(int, String)}
  45. */
  46. private static final Pattern date_ptrn1 = Pattern.compile("^\\[\\$\\-.*?\\]");
  47. private static final Pattern date_ptrn2 = Pattern.compile("^\\[[a-zA-Z]+\\]");
  48. private static final Pattern date_ptrn3a = Pattern.compile("[yYmMdDhHsS]");
  49. private static final Pattern date_ptrn3b = Pattern.compile("^[\\[\\]yYmMdDhHsS\\-T/,. :\"\\\\]+0*[ampAMP/]*$");
  50. // elapsed time patterns: [h],[m] and [s]
  51. private static final Pattern date_ptrn4 = Pattern.compile("^\\[([hH]+|[mM]+|[sS]+)\\]");
  52. // only get this static info once (because operations are not really cheap)
  53. private static final TimeZone TIMEZONE_UTC = TimeZone.getTimeZone("UTC");
  54. /**
  55. * Given a Date, converts it into a double representing its internal Excel representation,
  56. * which is the number of days since 1/1/1900. Fractional days represent hours, minutes, and seconds.
  57. *
  58. * @return Excel representation of Date (-1 if error - test for error by checking for less than 0.1)
  59. * @param date the Date
  60. */
  61. public static double getExcelDate(Date date) {
  62. return getExcelDate(date, false);
  63. }
  64. /**
  65. * Given a Date, converts it into a double representing its internal Excel representation,
  66. * which is the number of days since 1/1/1900. Fractional days represent hours, minutes, and seconds.
  67. *
  68. * @return Excel representation of Date (-1 if error - test for error by checking for less than 0.1)
  69. * @param date the Date
  70. * @param use1904windowing Should 1900 or 1904 date windowing be used?
  71. */
  72. public static double getExcelDate(Date date, boolean use1904windowing) {
  73. Calendar calStart = new GregorianCalendar();
  74. calStart.setTime(date); // If date includes hours, minutes, and seconds, set them to 0
  75. return internalGetExcelDate(calStart, use1904windowing);
  76. }
  77. /**
  78. * Given a Date in the form of a Calendar, converts it into a double
  79. * representing its internal Excel representation, which is the
  80. * number of days since 1/1/1900. Fractional days represent hours,
  81. * minutes, and seconds.
  82. *
  83. * @return Excel representation of Date (-1 if error - test for error by checking for less than 0.1)
  84. * @param date the Calendar holding the date to convert
  85. * @param use1904windowing Should 1900 or 1904 date windowing be used?
  86. */
  87. public static double getExcelDate(Calendar date, boolean use1904windowing) {
  88. // Don't alter the supplied Calendar as we do our work
  89. return internalGetExcelDate( (Calendar)date.clone(), use1904windowing );
  90. }
  91. private static double internalGetExcelDate(Calendar date, boolean use1904windowing) {
  92. if ((!use1904windowing && date.get(Calendar.YEAR) < 1900) ||
  93. (use1904windowing && date.get(Calendar.YEAR) < 1904))
  94. {
  95. return BAD_DATE;
  96. }
  97. // Because of daylight time saving we cannot use
  98. // date.getTime() - calStart.getTimeInMillis()
  99. // as the difference in milliseconds between 00:00 and 04:00
  100. // can be 3, 4 or 5 hours but Excel expects it to always
  101. // be 4 hours.
  102. // E.g. 2004-03-28 04:00 CEST - 2004-03-28 00:00 CET is 3 hours
  103. // and 2004-10-31 04:00 CET - 2004-10-31 00:00 CEST is 5 hours
  104. double fraction = (((date.get(Calendar.HOUR_OF_DAY) * 60
  105. + date.get(Calendar.MINUTE)
  106. ) * 60 + date.get(Calendar.SECOND)
  107. ) * 1000 + date.get(Calendar.MILLISECOND)
  108. ) / ( double ) DAY_MILLISECONDS;
  109. Calendar calStart = dayStart(date);
  110. double value = fraction + absoluteDay(calStart, use1904windowing);
  111. if (!use1904windowing && value >= 60) {
  112. value++;
  113. } else if (use1904windowing) {
  114. value--;
  115. }
  116. return value;
  117. }
  118. /**
  119. * Given an Excel date with using 1900 date windowing, and
  120. * converts it to a java.util.Date.
  121. *
  122. * Excel Dates and Times are stored without any timezone
  123. * information. If you know (through other means) that your file
  124. * uses a different TimeZone to the system default, you can use
  125. * this version of the getJavaDate() method to handle it.
  126. *
  127. * @param date The Excel date.
  128. * @param tz The TimeZone to evaluate the date in
  129. * @return Java representation of the date, or null if date is not a valid Excel date
  130. */
  131. public static Date getJavaDate(double date, TimeZone tz) {
  132. return getJavaDate(date, false, tz);
  133. }
  134. /**
  135. * Given an Excel date with using 1900 date windowing, and
  136. * converts it to a java.util.Date.
  137. *
  138. * NOTE: If the default <code>TimeZone</code> in Java uses Daylight
  139. * Saving Time then the conversion back to an Excel date may not give
  140. * the same value, that is the comparison
  141. * <CODE>excelDate == getExcelDate(getJavaDate(excelDate,false))</CODE>
  142. * is not always true. For example if default timezone is
  143. * <code>Europe/Copenhagen</code>, on 2004-03-28 the minute after
  144. * 01:59 CET is 03:00 CEST, if the excel date represents a time between
  145. * 02:00 and 03:00 then it is converted to past 03:00 summer time
  146. *
  147. * @param date The Excel date.
  148. * @return Java representation of the date, or null if date is not a valid Excel date
  149. * @see java.util.TimeZone
  150. */
  151. public static Date getJavaDate(double date) {
  152. return getJavaDate(date, (TimeZone)null);
  153. }
  154. /**
  155. * Given an Excel date with either 1900 or 1904 date windowing,
  156. * converts it to a java.util.Date.
  157. *
  158. * Excel Dates and Times are stored without any timezone
  159. * information. If you know (through other means) that your file
  160. * uses a different TimeZone to the system default, you can use
  161. * this version of the getJavaDate() method to handle it.
  162. *
  163. * @param date The Excel date.
  164. * @param tz The TimeZone to evaluate the date in
  165. * @param use1904windowing true if date uses 1904 windowing,
  166. * or false if using 1900 date windowing.
  167. * @return Java representation of the date, or null if date is not a valid Excel date
  168. */
  169. public static Date getJavaDate(double date, boolean use1904windowing, TimeZone tz) {
  170. return getJavaCalendar(date, use1904windowing, tz, false).getTime();
  171. }
  172. /**
  173. * Given an Excel date with either 1900 or 1904 date windowing,
  174. * converts it to a java.util.Date.
  175. *
  176. * Excel Dates and Times are stored without any timezone
  177. * information. If you know (through other means) that your file
  178. * uses a different TimeZone to the system default, you can use
  179. * this version of the getJavaDate() method to handle it.
  180. *
  181. * @param date The Excel date.
  182. * @param tz The TimeZone to evaluate the date in
  183. * @param use1904windowing true if date uses 1904 windowing,
  184. * or false if using 1900 date windowing.
  185. * @param roundSeconds round to closest second
  186. * @return Java representation of the date, or null if date is not a valid Excel date
  187. */
  188. public static Date getJavaDate(double date, boolean use1904windowing, TimeZone tz, boolean roundSeconds) {
  189. return getJavaCalendar(date, use1904windowing, tz, roundSeconds).getTime();
  190. }
  191. /**
  192. * Given an Excel date with either 1900 or 1904 date windowing,
  193. * converts it to a java.util.Date.
  194. *
  195. * NOTE: If the default <code>TimeZone</code> in Java uses Daylight
  196. * Saving Time then the conversion back to an Excel date may not give
  197. * the same value, that is the comparison
  198. * <CODE>excelDate == getExcelDate(getJavaDate(excelDate,false))</CODE>
  199. * is not always true. For example if default timezone is
  200. * <code>Europe/Copenhagen</code>, on 2004-03-28 the minute after
  201. * 01:59 CET is 03:00 CEST, if the excel date represents a time between
  202. * 02:00 and 03:00 then it is converted to past 03:00 summer time
  203. *
  204. * @param date The Excel date.
  205. * @param use1904windowing true if date uses 1904 windowing,
  206. * or false if using 1900 date windowing.
  207. * @return Java representation of the date, or null if date is not a valid Excel date
  208. * @see java.util.TimeZone
  209. */
  210. public static Date getJavaDate(double date, boolean use1904windowing) {
  211. return getJavaCalendar(date, use1904windowing, null, false).getTime();
  212. }
  213. public static void setCalendar(Calendar calendar, int wholeDays,
  214. int millisecondsInDay, boolean use1904windowing, boolean roundSeconds) {
  215. int startYear = 1900;
  216. int dayAdjust = -1; // Excel thinks 2/29/1900 is a valid date, which it isn't
  217. if (use1904windowing) {
  218. startYear = 1904;
  219. dayAdjust = 1; // 1904 date windowing uses 1/2/1904 as the first day
  220. }
  221. else if (wholeDays < 61) {
  222. // Date is prior to 3/1/1900, so adjust because Excel thinks 2/29/1900 exists
  223. // If Excel date == 2/29/1900, will become 3/1/1900 in Java representation
  224. dayAdjust = 0;
  225. }
  226. calendar.set(startYear,0, wholeDays + dayAdjust, 0, 0, 0);
  227. calendar.set(Calendar.MILLISECOND, millisecondsInDay);
  228. if (roundSeconds) {
  229. calendar.add(Calendar.MILLISECOND, 500);
  230. calendar.clear(Calendar.MILLISECOND);
  231. }
  232. }
  233. /**
  234. * Get EXCEL date as Java Calendar (with default time zone).
  235. * This is like {@link #getJavaDate(double)} but returns a Calendar object.
  236. * @param date The Excel date.
  237. * @return Java representation of the date, or null if date is not a valid Excel date
  238. */
  239. public static Calendar getJavaCalendar(double date) {
  240. return getJavaCalendar(date, false, (TimeZone)null, false);
  241. }
  242. /**
  243. * Get EXCEL date as Java Calendar (with default time zone).
  244. * This is like {@link #getJavaDate(double, boolean)} but returns a Calendar object.
  245. * @param date The Excel date.
  246. * @param use1904windowing true if date uses 1904 windowing,
  247. * or false if using 1900 date windowing.
  248. * @return Java representation of the date, or null if date is not a valid Excel date
  249. */
  250. public static Calendar getJavaCalendar(double date, boolean use1904windowing) {
  251. return getJavaCalendar(date, use1904windowing, (TimeZone)null, false);
  252. }
  253. /**
  254. * Get EXCEL date as Java Calendar with UTC time zone.
  255. * This is similar to {@link #getJavaDate(double, boolean)} but returns a
  256. * Calendar object that has UTC as time zone, so no daylight saving hassle.
  257. * @param date The Excel date.
  258. * @param use1904windowing true if date uses 1904 windowing,
  259. * or false if using 1900 date windowing.
  260. * @return Java representation of the date in UTC, or null if date is not a valid Excel date
  261. */
  262. public static Calendar getJavaCalendarUTC(double date, boolean use1904windowing) {
  263. return getJavaCalendar(date, use1904windowing, TIMEZONE_UTC, false);
  264. }
  265. /**
  266. * Get EXCEL date as Java Calendar with given time zone.
  267. * @param date The Excel date.
  268. * @param use1904windowing true if date uses 1904 windowing,
  269. * or false if using 1900 date windowing.
  270. * @param timeZone The TimeZone to evaluate the date in
  271. * @return Java representation of the date, or null if date is not a valid Excel date
  272. */
  273. public static Calendar getJavaCalendar(double date, boolean use1904windowing, TimeZone timeZone) {
  274. return getJavaCalendar(date, use1904windowing, timeZone, false);
  275. }
  276. /**
  277. * Get EXCEL date as Java Calendar with given time zone.
  278. * @param date The Excel date.
  279. * @param use1904windowing true if date uses 1904 windowing,
  280. * or false if using 1900 date windowing.
  281. * @param timeZone The TimeZone to evaluate the date in
  282. * @param roundSeconds round to closest second
  283. * @return Java representation of the date, or null if date is not a valid Excel date
  284. */
  285. public static Calendar getJavaCalendar(double date, boolean use1904windowing, TimeZone timeZone, boolean roundSeconds) {
  286. if (!isValidExcelDate(date)) {
  287. return null;
  288. }
  289. int wholeDays = (int)Math.floor(date);
  290. int millisecondsInDay = (int)((date - wholeDays) * DAY_MILLISECONDS + 0.5);
  291. Calendar calendar;
  292. if (timeZone != null) {
  293. calendar = new GregorianCalendar(timeZone);
  294. } else {
  295. calendar = new GregorianCalendar(); // using default time-zone
  296. }
  297. setCalendar(calendar, wholeDays, millisecondsInDay, use1904windowing, roundSeconds);
  298. return calendar;
  299. }
  300. // variables for performance optimization:
  301. // avoid re-checking DataUtil.isADateFormat(int, String) if a given format
  302. // string represents a date format if the same string is passed multiple times.
  303. // see https://issues.apache.org/bugzilla/show_bug.cgi?id=55611
  304. private static int lastFormatIndex = -1;
  305. private static String lastFormatString = null;
  306. private static boolean cached = false;
  307. /**
  308. * Given a format ID and its format String, will check to see if the
  309. * format represents a date format or not.
  310. * Firstly, it will check to see if the format ID corresponds to an
  311. * internal excel date format (eg most US date formats)
  312. * If not, it will check to see if the format string only contains
  313. * date formatting characters (ymd-/), which covers most
  314. * non US date formats.
  315. *
  316. * @param formatIndex The index of the format, eg from ExtendedFormatRecord.getFormatIndex
  317. * @param formatString The format string, eg from FormatRecord.getFormatString
  318. * @see #isInternalDateFormat(int)
  319. */
  320. public static synchronized boolean isADateFormat(int formatIndex, String formatString) {
  321. if (formatString != null && formatIndex == lastFormatIndex && formatString.equals(lastFormatString)) {
  322. return cached;
  323. }
  324. // First up, is this an internal date format?
  325. if(isInternalDateFormat(formatIndex)) {
  326. lastFormatIndex = formatIndex;
  327. lastFormatString = formatString;
  328. cached = true;
  329. return true;
  330. }
  331. // If we didn't get a real string, it can't be
  332. if(formatString == null || formatString.length() == 0) {
  333. lastFormatIndex = formatIndex;
  334. lastFormatString = formatString;
  335. cached = false;
  336. return false;
  337. }
  338. String fs = formatString;
  339. /*if (false) {
  340. // Normalize the format string. The code below is equivalent
  341. // to the following consecutive regexp replacements:
  342. // Translate \- into just -, before matching
  343. fs = fs.replaceAll("\\\\-","-");
  344. // And \, into ,
  345. fs = fs.replaceAll("\\\\,",",");
  346. // And \. into .
  347. fs = fs.replaceAll("\\\\\\.",".");
  348. // And '\ ' into ' '
  349. fs = fs.replaceAll("\\\\ "," ");
  350. // If it end in ;@, that's some crazy dd/mm vs mm/dd
  351. // switching stuff, which we can ignore
  352. fs = fs.replaceAll(";@", "");
  353. // The code above was reworked as suggested in bug 48425:
  354. // simple loop is more efficient than consecutive regexp replacements.
  355. }*/
  356. StringBuilder sb = new StringBuilder(fs.length());
  357. for (int i = 0; i < fs.length(); i++) {
  358. char c = fs.charAt(i);
  359. if (i < fs.length() - 1) {
  360. char nc = fs.charAt(i + 1);
  361. if (c == '\\') {
  362. switch (nc) {
  363. case '-':
  364. case ',':
  365. case '.':
  366. case ' ':
  367. case '\\':
  368. // skip current '\' and continue to the next char
  369. continue;
  370. }
  371. } else if (c == ';' && nc == '@') {
  372. i++;
  373. // skip ";@" duplets
  374. continue;
  375. }
  376. }
  377. sb.append(c);
  378. }
  379. fs = sb.toString();
  380. // short-circuit if it indicates elapsed time: [h], [m] or [s]
  381. if(date_ptrn4.matcher(fs).matches()){
  382. lastFormatIndex = formatIndex;
  383. lastFormatString = formatString;
  384. cached = true;
  385. return true;
  386. }
  387. // If it starts with [$-...], then could be a date, but
  388. // who knows what that starting bit is all about
  389. fs = date_ptrn1.matcher(fs).replaceAll("");
  390. // If it starts with something like [Black] or [Yellow],
  391. // then it could be a date
  392. fs = date_ptrn2.matcher(fs).replaceAll("");
  393. // You're allowed something like dd/mm/yy;[red]dd/mm/yy
  394. // which would place dates before 1900/1904 in red
  395. // For now, only consider the first one
  396. if(fs.indexOf(';') > 0 && fs.indexOf(';') < fs.length()-1) {
  397. fs = fs.substring(0, fs.indexOf(';'));
  398. }
  399. // Ensure it has some date letters in it
  400. // (Avoids false positives on the rest of pattern 3)
  401. if (! date_ptrn3a.matcher(fs).find()) {
  402. return false;
  403. }
  404. // If we get here, check it's only made up, in any case, of:
  405. // y m d h s - \ / , . : [ ] T
  406. // optionally followed by AM/PM
  407. boolean result = date_ptrn3b.matcher(fs).matches();
  408. lastFormatIndex = formatIndex;
  409. lastFormatString = formatString;
  410. cached = result;
  411. return result;
  412. }
  413. /**
  414. * Given a format ID this will check whether the format represents
  415. * an internal excel date format or not.
  416. * @see #isADateFormat(int, java.lang.String)
  417. */
  418. public static boolean isInternalDateFormat(int format) {
  419. switch(format) {
  420. // Internal Date Formats as described on page 427 in
  421. // Microsoft Excel Dev's Kit...
  422. case 0x0e:
  423. case 0x0f:
  424. case 0x10:
  425. case 0x11:
  426. case 0x12:
  427. case 0x13:
  428. case 0x14:
  429. case 0x15:
  430. case 0x16:
  431. case 0x2d:
  432. case 0x2e:
  433. case 0x2f:
  434. return true;
  435. }
  436. return false;
  437. }
  438. /**
  439. * Check if a cell contains a date
  440. * Since dates are stored internally in Excel as double values
  441. * we infer it is a date if it is formatted as such.
  442. * @see #isADateFormat(int, String)
  443. * @see #isInternalDateFormat(int)
  444. */
  445. public static boolean isCellDateFormatted(Cell cell) {
  446. if (cell == null) return false;
  447. boolean bDate = false;
  448. double d = cell.getNumericCellValue();
  449. if ( DateUtil.isValidExcelDate(d) ) {
  450. CellStyle style = cell.getCellStyle();
  451. if(style==null) return false;
  452. int i = style.getDataFormat();
  453. String f = style.getDataFormatString();
  454. bDate = isADateFormat(i, f);
  455. }
  456. return bDate;
  457. }
  458. /**
  459. * Check if a cell contains a date, checking only for internal
  460. * excel date formats.
  461. * As Excel stores a great many of its dates in "non-internal"
  462. * date formats, you will not normally want to use this method.
  463. * @see #isADateFormat(int,String)
  464. * @see #isInternalDateFormat(int)
  465. */
  466. public static boolean isCellInternalDateFormatted(Cell cell) {
  467. if (cell == null) return false;
  468. boolean bDate = false;
  469. double d = cell.getNumericCellValue();
  470. if ( DateUtil.isValidExcelDate(d) ) {
  471. CellStyle style = cell.getCellStyle();
  472. int i = style.getDataFormat();
  473. bDate = isInternalDateFormat(i);
  474. }
  475. return bDate;
  476. }
  477. /**
  478. * Given a double, checks if it is a valid Excel date.
  479. *
  480. * @return true if valid
  481. * @param value the double value
  482. */
  483. public static boolean isValidExcelDate(double value)
  484. {
  485. return (value > -Double.MIN_VALUE);
  486. }
  487. /**
  488. * Given a Calendar, return the number of days since 1900/12/31.
  489. *
  490. * @return days number of days since 1900/12/31
  491. * @param cal the Calendar
  492. * @exception IllegalArgumentException if date is invalid
  493. */
  494. protected static int absoluteDay(Calendar cal, boolean use1904windowing)
  495. {
  496. return cal.get(Calendar.DAY_OF_YEAR)
  497. + daysInPriorYears(cal.get(Calendar.YEAR), use1904windowing);
  498. }
  499. /**
  500. * Return the number of days in prior years since 1900
  501. *
  502. * @return days number of days in years prior to yr.
  503. * @param yr a year (1900 < yr < 4000)
  504. * @param use1904windowing
  505. * @exception IllegalArgumentException if year is outside of range.
  506. */
  507. private static int daysInPriorYears(int yr, boolean use1904windowing)
  508. {
  509. if ((!use1904windowing && yr < 1900) || (use1904windowing && yr < 1900)) {
  510. throw new IllegalArgumentException("'year' must be 1900 or greater");
  511. }
  512. int yr1 = yr - 1;
  513. int leapDays = yr1 / 4 // plus julian leap days in prior years
  514. - yr1 / 100 // minus prior century years
  515. + yr1 / 400 // plus years divisible by 400
  516. - 460; // leap days in previous 1900 years
  517. return 365 * (yr - (use1904windowing ? 1904 : 1900)) + leapDays;
  518. }
  519. // set HH:MM:SS fields of cal to 00:00:00:000
  520. private static Calendar dayStart(final Calendar cal)
  521. {
  522. cal.get(Calendar
  523. .HOUR_OF_DAY); // force recalculation of internal fields
  524. cal.set(Calendar.HOUR_OF_DAY, 0);
  525. cal.set(Calendar.MINUTE, 0);
  526. cal.set(Calendar.SECOND, 0);
  527. cal.set(Calendar.MILLISECOND, 0);
  528. cal.get(Calendar
  529. .HOUR_OF_DAY); // force recalculation of internal fields
  530. return cal;
  531. }
  532. @SuppressWarnings("serial")
  533. private static final class FormatException extends Exception {
  534. public FormatException(String msg) {
  535. super(msg);
  536. }
  537. }
  538. /**
  539. * Converts a string of format "HH:MM" or "HH:MM:SS" to its (Excel) numeric equivalent
  540. *
  541. * @return a double between 0 and 1 representing the fraction of the day
  542. */
  543. public static double convertTime(String timeStr) {
  544. try {
  545. return convertTimeInternal(timeStr);
  546. } catch (FormatException e) {
  547. String msg = "Bad time format '" + timeStr
  548. + "' expected 'HH:MM' or 'HH:MM:SS' - " + e.getMessage();
  549. throw new IllegalArgumentException(msg);
  550. }
  551. }
  552. private static double convertTimeInternal(String timeStr) throws FormatException {
  553. int len = timeStr.length();
  554. if (len < 4 || len > 8) {
  555. throw new FormatException("Bad length");
  556. }
  557. String[] parts = TIME_SEPARATOR_PATTERN.split(timeStr);
  558. String secStr;
  559. switch (parts.length) {
  560. case 2: secStr = "00"; break;
  561. case 3: secStr = parts[2]; break;
  562. default:
  563. throw new FormatException("Expected 2 or 3 fields but got (" + parts.length + ")");
  564. }
  565. String hourStr = parts[0];
  566. String minStr = parts[1];
  567. int hours = parseInt(hourStr, "hour", HOURS_PER_DAY);
  568. int minutes = parseInt(minStr, "minute", MINUTES_PER_HOUR);
  569. int seconds = parseInt(secStr, "second", SECONDS_PER_MINUTE);
  570. double totalSeconds = seconds + (minutes + (hours) * 60) * 60;
  571. return totalSeconds / (SECONDS_PER_DAY);
  572. }
  573. /**
  574. * Converts a string of format "YYYY/MM/DD" to its (Excel) numeric equivalent
  575. *
  576. * @return a double representing the (integer) number of days since the start of the Excel epoch
  577. */
  578. public static Date parseYYYYMMDDDate(String dateStr) {
  579. try {
  580. return parseYYYYMMDDDateInternal(dateStr);
  581. } catch (FormatException e) {
  582. String msg = "Bad time format " + dateStr
  583. + " expected 'YYYY/MM/DD' - " + e.getMessage();
  584. throw new IllegalArgumentException(msg);
  585. }
  586. }
  587. private static Date parseYYYYMMDDDateInternal(String timeStr) throws FormatException {
  588. if(timeStr.length() != 10) {
  589. throw new FormatException("Bad length");
  590. }
  591. String yearStr = timeStr.substring(0, 4);
  592. String monthStr = timeStr.substring(5, 7);
  593. String dayStr = timeStr.substring(8, 10);
  594. int year = parseInt(yearStr, "year", Short.MIN_VALUE, Short.MAX_VALUE);
  595. int month = parseInt(monthStr, "month", 1, 12);
  596. int day = parseInt(dayStr, "day", 1, 31);
  597. Calendar cal = new GregorianCalendar(year, month-1, day, 0, 0, 0);
  598. cal.set(Calendar.MILLISECOND, 0);
  599. return cal.getTime();
  600. }
  601. private static int parseInt(String strVal, String fieldName, int rangeMax) throws FormatException {
  602. return parseInt(strVal, fieldName, 0, rangeMax-1);
  603. }
  604. private static int parseInt(String strVal, String fieldName, int lowerLimit, int upperLimit) throws FormatException {
  605. int result;
  606. try {
  607. result = Integer.parseInt(strVal);
  608. } catch (NumberFormatException e) {
  609. throw new FormatException("Bad int format '" + strVal + "' for " + fieldName + " field");
  610. }
  611. if (result < lowerLimit || result > upperLimit) {
  612. throw new FormatException(fieldName + " value (" + result
  613. + ") is outside the allowable range(0.." + upperLimit + ")");
  614. }
  615. return result;
  616. }
  617. }