Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

DateUtil.java 30KB

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