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 40KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993
  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.math.BigDecimal;
  17. import java.time.LocalDate;
  18. import java.time.LocalDateTime;
  19. import java.time.LocalTime;
  20. import java.time.ZoneId;
  21. import java.time.format.DateTimeFormatter;
  22. import java.time.format.DateTimeFormatterBuilder;
  23. import java.time.temporal.ChronoField;
  24. import java.time.temporal.ChronoUnit;
  25. import java.time.temporal.TemporalAccessor;
  26. import java.time.temporal.TemporalQueries;
  27. import java.util.Calendar;
  28. import java.util.Date;
  29. import java.util.TimeZone;
  30. import java.util.regex.Pattern;
  31. import org.apache.poi.ss.formula.ConditionalFormattingEvaluator;
  32. import org.apache.poi.util.LocaleUtil;
  33. /**
  34. * Contains methods for dealing with Excel dates.
  35. */
  36. public class DateUtil {
  37. // FIXME this should be changed to private and the class marked final once HSSFDateUtil can be removed
  38. protected DateUtil() {
  39. // no instances of this class
  40. }
  41. public static final int SECONDS_PER_MINUTE = 60;
  42. public static final int MINUTES_PER_HOUR = 60;
  43. public static final int HOURS_PER_DAY = 24;
  44. public static final int SECONDS_PER_DAY = (HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE);
  45. // used to specify that date is invalid
  46. private static final int BAD_DATE = -1;
  47. public static final long DAY_MILLISECONDS = SECONDS_PER_DAY * 1000L;
  48. private static final BigDecimal BD_NANOSEC_DAY = BigDecimal.valueOf(SECONDS_PER_DAY * 1e9);
  49. private static final BigDecimal BD_MILISEC_RND = BigDecimal.valueOf(0.5 * 1e6);
  50. private static final BigDecimal BD_SECOND_RND = BigDecimal.valueOf(0.5 * 1e9);
  51. private static final Pattern TIME_SEPARATOR_PATTERN = Pattern.compile(":");
  52. /**
  53. * The following patterns are used in {@link #isADateFormat(int, String)}
  54. */
  55. private static final Pattern date_ptrn1 = Pattern.compile("^\\[\\$-.*?]");
  56. private static final Pattern date_ptrn2 = Pattern.compile("^\\[[a-zA-Z]+]");
  57. private static final Pattern date_ptrn3a = Pattern.compile("[yYmMdDhHsS]");
  58. // add "\u5e74 \u6708 \u65e5" for Chinese/Japanese date format:2017 \u5e74 2 \u6708 7 \u65e5
  59. private static final Pattern date_ptrn3b = Pattern.compile("^[\\[\\]yYmMdDhHsS\\-T/\u5e74\u6708\u65e5,. :\"\\\\]+0*[ampAMP/]*$");
  60. // elapsed time patterns: [h],[m] and [s]
  61. private static final Pattern date_ptrn4 = Pattern.compile("^\\[([hH]+|[mM]+|[sS]+)]");
  62. // for format which start with "[DBNum1]" or "[DBNum2]" or "[DBNum3]" could be a Chinese date
  63. private static final Pattern date_ptrn5 = Pattern.compile("^\\[DBNum([123])]");
  64. private static final DateTimeFormatter dateTimeFormats = new DateTimeFormatterBuilder()
  65. .appendPattern("[dd MMM[ yyyy]][[ ]h:m[:s][.SSS] a][[ ]H:m[:s][.SSS]]")
  66. .appendPattern("[[yyyy ]dd-MMM[-yyyy]][[ ]h:m[:s][.SSS] a][[ ]H:m[:s][.SSS]]")
  67. .appendPattern("[M/dd[/yyyy]][[ ]h:m[:s][.SSS] a][[ ]H:m[:s][.SSS]]")
  68. .appendPattern("[[yyyy/]M/dd][[ ]h:m[:s][.SSS] a][[ ]H:m[:s][.SSS]]")
  69. .parseDefaulting(ChronoField.YEAR_OF_ERA, LocaleUtil.getLocaleCalendar().get(Calendar.YEAR))
  70. .toFormatter(LocaleUtil.getUserLocale());
  71. /**
  72. * Convert a Java Date (at UTC) to LocalDateTime.
  73. * @param date the date
  74. * @return LocalDateTime instance
  75. */
  76. public static LocalDateTime toLocalDateTime(Date date) {
  77. return date.toInstant()
  78. .atZone(TimeZone.getTimeZone("UTC").toZoneId()) // java.util.Date uses UTC
  79. .toLocalDateTime();
  80. }
  81. /**
  82. * Convert a Java Calendar (at UTC) to LocalDateTime.
  83. * @param date the date
  84. * @return LocalDateTime instance
  85. */
  86. public static LocalDateTime toLocalDateTime(Calendar date) {
  87. return date.toInstant()
  88. .atZone(TimeZone.getTimeZone("UTC").toZoneId()) // java.util.Date uses UTC
  89. .toLocalDateTime();
  90. }
  91. /**
  92. * Given a LocalDate, converts it into a double representing its internal Excel representation,
  93. * which is the number of days since 1/1/1900. Fractional days represent hours, minutes, and seconds.
  94. *
  95. * @return Excel representation of Date (-1 if error - test for error by checking for less than 0.1)
  96. * @param date the Date
  97. */
  98. public static double getExcelDate(LocalDate date) {
  99. return getExcelDate(date, false);
  100. }
  101. /**
  102. * Given a LocalDate, converts it into a double representing its internal Excel representation,
  103. * which is the number of days since 1/1/1900. Fractional days represent hours, minutes, and seconds.
  104. *
  105. * @return Excel representation of Date (-1 if error - test for error by checking for less than 0.1)
  106. * @param date the Date
  107. * @param use1904windowing Should 1900 or 1904 date windowing be used?
  108. */
  109. public static double getExcelDate(LocalDate date, boolean use1904windowing) {
  110. int year = date.getYear();
  111. int dayOfYear = date.getDayOfYear();
  112. int hour = 0;
  113. int minute = 0;
  114. int second = 0;
  115. int milliSecond = 0;
  116. return internalGetExcelDate(year, dayOfYear, hour, minute, second, milliSecond, use1904windowing);
  117. }
  118. /**
  119. * Given a LocalDateTime, converts it into a double representing its internal Excel representation,
  120. * which is the number of days since 1/1/1900. Fractional days represent hours, minutes, and seconds.
  121. *
  122. * @return Excel representation of Date (-1 if error - test for error by checking for less than 0.1)
  123. * @param date the Date
  124. */
  125. public static double getExcelDate(LocalDateTime date) {
  126. return getExcelDate(date, false);
  127. }
  128. /**
  129. * Given a LocalDateTime, converts it into a double representing its internal Excel representation,
  130. * which is the number of days since 1/1/1900. Fractional days represent hours, minutes, and seconds.
  131. *
  132. * @return Excel representation of Date (-1 if error - test for error by checking for less than 0.1)
  133. * @param date the Date
  134. * @param use1904windowing Should 1900 or 1904 date windowing be used?
  135. */
  136. public static double getExcelDate(LocalDateTime date, boolean use1904windowing) {
  137. int year = date.getYear();
  138. int dayOfYear = date.getDayOfYear();
  139. int hour = date.getHour();
  140. int minute = date.getMinute();
  141. int second = date.getSecond();
  142. int milliSecond = date.getNano()/1_000_000;
  143. return internalGetExcelDate(year, dayOfYear, hour, minute, second, milliSecond, use1904windowing);
  144. }
  145. /**
  146. * Given a Date, converts it into a double representing its internal Excel representation,
  147. * which is the number of days since 1/1/1900. Fractional days represent hours, minutes, and seconds.
  148. *
  149. * @return Excel representation of Date (-1 if error - test for error by checking for less than 0.1)
  150. * @param date the Date
  151. */
  152. public static double getExcelDate(Date date) {
  153. return getExcelDate(date, false);
  154. }
  155. /**
  156. * Given a Date, converts it into a double representing its internal Excel representation,
  157. * which is the number of days since 1/1/1900. Fractional days represent hours, minutes, and seconds.
  158. *
  159. * @return Excel representation of Date (-1 if error - test for error by checking for less than 0.1)
  160. * @param date the Date
  161. * @param use1904windowing Should 1900 or 1904 date windowing be used?
  162. */
  163. public static double getExcelDate(Date date, boolean use1904windowing) {
  164. Calendar calStart = LocaleUtil.getLocaleCalendar();
  165. calStart.setTime(date);
  166. int year = calStart.get(Calendar.YEAR);
  167. int dayOfYear = calStart.get(Calendar.DAY_OF_YEAR);
  168. int hour = calStart.get(Calendar.HOUR_OF_DAY);
  169. int minute = calStart.get(Calendar.MINUTE);
  170. int second = calStart.get(Calendar.SECOND);
  171. int milliSecond = calStart.get(Calendar.MILLISECOND);
  172. return internalGetExcelDate(year, dayOfYear, hour, minute, second, milliSecond, use1904windowing);
  173. }
  174. /**
  175. * Given a Date in the form of a Calendar, converts it into a double
  176. * representing its internal Excel representation, which is the
  177. * number of days since 1/1/1900. Fractional days represent hours,
  178. * minutes, and seconds.
  179. *
  180. * @return Excel representation of Date (-1 if error - test for error by checking for less than 0.1)
  181. * @param date the Calendar holding the date to convert
  182. * @param use1904windowing Should 1900 or 1904 date windowing be used?
  183. */
  184. public static double getExcelDate(Calendar date, boolean use1904windowing) {
  185. int year = date.get(Calendar.YEAR);
  186. int dayOfYear = date.get(Calendar.DAY_OF_YEAR);
  187. int hour = date.get(Calendar.HOUR_OF_DAY);
  188. int minute = date.get(Calendar.MINUTE);
  189. int second = date.get(Calendar.SECOND);
  190. int milliSecond = date.get(Calendar.MILLISECOND);
  191. return internalGetExcelDate(year, dayOfYear, hour, minute, second, milliSecond, use1904windowing);
  192. }
  193. private static double internalGetExcelDate(int year, int dayOfYear, int hour, int minute, int second, int milliSecond, boolean use1904windowing) {
  194. if ((!use1904windowing && year < 1900) ||
  195. (use1904windowing && year < 1904))
  196. {
  197. return BAD_DATE;
  198. }
  199. // Because of daylight time saving we cannot use
  200. // date.getTime() - calStart.getTimeInMillis()
  201. // as the difference in milliseconds between 00:00 and 04:00
  202. // can be 3, 4 or 5 hours but Excel expects it to always
  203. // be 4 hours.
  204. // E.g. 2004-03-28 04:00 CEST - 2004-03-28 00:00 CET is 3 hours
  205. // and 2004-10-31 04:00 CET - 2004-10-31 00:00 CEST is 5 hours
  206. double fraction = (((hour * 60.0
  207. + minute
  208. ) * 60.0 + second
  209. ) * 1000.0 + milliSecond
  210. ) / DAY_MILLISECONDS;
  211. double value = fraction + absoluteDay(year, dayOfYear, use1904windowing);
  212. if (!use1904windowing && value >= 60) {
  213. value++;
  214. } else if (use1904windowing) {
  215. value--;
  216. }
  217. return value;
  218. }
  219. /**
  220. * Given an Excel date with using 1900 date windowing, and
  221. * converts it to a java.util.Date.
  222. *
  223. * Excel Dates and Times are stored without any timezone
  224. * information. If you know (through other means) that your file
  225. * uses a different TimeZone to the system default, you can use
  226. * this version of the getJavaDate() method to handle it.
  227. *
  228. * @param date The Excel date.
  229. * @param tz The TimeZone to evaluate the date in
  230. * @return Java representation of the date, or null if date is not a valid Excel date
  231. */
  232. public static Date getJavaDate(double date, TimeZone tz) {
  233. return getJavaDate(date, false, tz, false);
  234. }
  235. /**
  236. * Given an Excel date with using 1900 date windowing, and
  237. * converts it to a java.util.Date.
  238. *
  239. * NOTE: If the default <code>TimeZone</code> in Java uses Daylight
  240. * Saving Time then the conversion back to an Excel date may not give
  241. * the same value, that is the comparison
  242. * <CODE>excelDate == getExcelDate(getJavaDate(excelDate,false))</CODE>
  243. * is not always true. For example if default timezone is
  244. * <code>Europe/Copenhagen</code>, on 2004-03-28 the minute after
  245. * 01:59 CET is 03:00 CEST, if the excel date represents a time between
  246. * 02:00 and 03:00 then it is converted to past 03:00 summer time
  247. *
  248. * @param date The Excel date.
  249. * @return Java representation of the date, or null if date is not a valid Excel date
  250. * @see java.util.TimeZone
  251. */
  252. public static Date getJavaDate(double date) {
  253. return getJavaDate(date, false, null, false);
  254. }
  255. /**
  256. * Given an Excel date with either 1900 or 1904 date windowing,
  257. * converts it to a java.util.Date.
  258. *
  259. * Excel Dates and Times are stored without any timezone
  260. * information. If you know (through other means) that your file
  261. * uses a different TimeZone to the system default, you can use
  262. * this version of the getJavaDate() method to handle it.
  263. *
  264. * @param date The Excel date.
  265. * @param tz The TimeZone to evaluate the date in
  266. * @param use1904windowing true if date uses 1904 windowing,
  267. * or false if using 1900 date windowing.
  268. * @return Java representation of the date, or null if date is not a valid Excel date
  269. */
  270. public static Date getJavaDate(double date, boolean use1904windowing, TimeZone tz) {
  271. return getJavaDate(date, use1904windowing, tz, false);
  272. }
  273. /**
  274. * Given an Excel date with either 1900 or 1904 date windowing,
  275. * converts it to a java.util.Date.
  276. *
  277. * Excel Dates and Times are stored without any timezone
  278. * information. If you know (through other means) that your file
  279. * uses a different TimeZone to the system default, you can use
  280. * this version of the getJavaDate() method to handle it.
  281. *
  282. * @param date The Excel date.
  283. * @param tz The TimeZone to evaluate the date in
  284. * @param use1904windowing true if date uses 1904 windowing,
  285. * or false if using 1900 date windowing.
  286. * @param roundSeconds round to closest second
  287. * @return Java representation of the date, or null if date is not a valid Excel date
  288. */
  289. public static Date getJavaDate(double date, boolean use1904windowing, TimeZone tz, boolean roundSeconds) {
  290. Calendar calendar = getJavaCalendar(date, use1904windowing, tz, roundSeconds);
  291. return calendar == null ? null : calendar.getTime();
  292. }
  293. /**
  294. * Given an Excel date with either 1900 or 1904 date windowing,
  295. * converts it to a java.util.Date.
  296. *
  297. * NOTE: If the default <code>TimeZone</code> in Java uses Daylight
  298. * Saving Time then the conversion back to an Excel date may not give
  299. * the same value, that is the comparison
  300. * <CODE>excelDate == getExcelDate(getJavaDate(excelDate,false))</CODE>
  301. * is not always true. For example if default timezone is
  302. * <code>Europe/Copenhagen</code>, on 2004-03-28 the minute after
  303. * 01:59 CET is 03:00 CEST, if the excel date represents a time between
  304. * 02:00 and 03:00 then it is converted to past 03:00 summer time
  305. *
  306. * @param date The Excel date.
  307. * @param use1904windowing true if date uses 1904 windowing,
  308. * or false if using 1900 date windowing.
  309. * @return Java representation of the date, or null if date is not a valid Excel date
  310. * @see java.util.TimeZone
  311. */
  312. public static Date getJavaDate(double date, boolean use1904windowing) {
  313. return getJavaDate(date, use1904windowing, null, false);
  314. }
  315. /**
  316. * Given an Excel date with using 1900 date windowing, and
  317. * converts it to a java.time.LocalDateTime.
  318. *
  319. * NOTE: If the default <code>TimeZone</code> in Java uses Daylight
  320. * Saving Time then the conversion back to an Excel date may not give
  321. * the same value, that is the comparison
  322. * <CODE>excelDate == getExcelDate(getLocalDateTime(excelDate,false))</CODE>
  323. * is not always true. For example if default timezone is
  324. * <code>Europe/Copenhagen</code>, on 2004-03-28 the minute after
  325. * 01:59 CET is 03:00 CEST, if the excel date represents a time between
  326. * 02:00 and 03:00 then it is converted to past 03:00 summer time
  327. *
  328. * @param date The Excel date.
  329. * @return Java representation of the date, or null if date is not a valid Excel date
  330. * @see java.util.TimeZone
  331. */
  332. public static LocalDateTime getLocalDateTime(double date) {
  333. return getLocalDateTime(date, false, false);
  334. }
  335. /**
  336. * Given an Excel date with either 1900 or 1904 date windowing,
  337. * converts it to a java.time.LocalDateTime.
  338. *
  339. * Excel Dates and Times are stored without any timezone
  340. * information. If you know (through other means) that your file
  341. * uses a different TimeZone to the system default, you can use
  342. * this version of the getJavaDate() method to handle it.
  343. *
  344. * @param date The Excel date.
  345. * @param use1904windowing true if date uses 1904 windowing,
  346. * or false if using 1900 date windowing.
  347. * @return Java representation of the date, or null if date is not a valid Excel date
  348. */
  349. public static LocalDateTime getLocalDateTime(double date, boolean use1904windowing) {
  350. return getLocalDateTime(date, use1904windowing, false);
  351. }
  352. /**
  353. * Given an Excel date with either 1900 or 1904 date windowing,
  354. * converts it to a java.time.LocalDateTime.
  355. *
  356. * Excel Dates and Times are stored without any timezone
  357. * information. If you know (through other means) that your file
  358. * uses a different TimeZone to the system default, you can use
  359. * this version of the getJavaDate() method to handle it.
  360. *
  361. * @param date The Excel date.
  362. * @param use1904windowing true if date uses 1904 windowing,
  363. * or false if using 1900 date windowing.
  364. * @param roundSeconds round to closest second
  365. * @return Java representation of the date, or null if date is not a valid Excel date
  366. */
  367. @SuppressWarnings("squid:S2111")
  368. public static LocalDateTime getLocalDateTime(double date, boolean use1904windowing, boolean roundSeconds) {
  369. if (!isValidExcelDate(date)) {
  370. return null;
  371. }
  372. BigDecimal bd = BigDecimal.valueOf(date);
  373. int wholeDays = bd.intValue();
  374. int startYear = 1900;
  375. int dayAdjust = -1; // Excel thinks 2/29/1900 is a valid date, which it isn't
  376. if (use1904windowing) {
  377. startYear = 1904;
  378. dayAdjust = 1; // 1904 date windowing uses 1/2/1904 as the first day
  379. }
  380. else if (wholeDays < 61) {
  381. // Date is prior to 3/1/1900, so adjust because Excel thinks 2/29/1900 exists
  382. // If Excel date == 2/29/1900, will become 3/1/1900 in Java representation
  383. dayAdjust = 0;
  384. }
  385. LocalDateTime ldt = LocalDateTime.of(startYear, 1, 1, 0, 0);
  386. ldt = ldt.plusDays(wholeDays+dayAdjust-1L);
  387. long nanosTime =
  388. bd.subtract(BigDecimal.valueOf(wholeDays))
  389. .multiply(BD_NANOSEC_DAY)
  390. .add(roundSeconds ? BD_SECOND_RND : BD_MILISEC_RND)
  391. .longValue();
  392. ldt = ldt.plusNanos(nanosTime);
  393. ldt = ldt.truncatedTo(roundSeconds ? ChronoUnit.SECONDS : ChronoUnit.MILLIS);
  394. return ldt;
  395. }
  396. public static void setCalendar(Calendar calendar, int wholeDays,
  397. int millisecondsInDay, boolean use1904windowing, boolean roundSeconds) {
  398. int startYear = 1900;
  399. int dayAdjust = -1; // Excel thinks 2/29/1900 is a valid date, which it isn't
  400. if (use1904windowing) {
  401. startYear = 1904;
  402. dayAdjust = 1; // 1904 date windowing uses 1/2/1904 as the first day
  403. }
  404. else if (wholeDays < 61) {
  405. // Date is prior to 3/1/1900, so adjust because Excel thinks 2/29/1900 exists
  406. // If Excel date == 2/29/1900, will become 3/1/1900 in Java representation
  407. dayAdjust = 0;
  408. }
  409. calendar.set(startYear, Calendar.JANUARY, wholeDays + dayAdjust, 0, 0, 0);
  410. calendar.set(Calendar.MILLISECOND, millisecondsInDay);
  411. if (calendar.get(Calendar.MILLISECOND) == 0) {
  412. calendar.clear(Calendar.MILLISECOND);
  413. }
  414. if (roundSeconds) {
  415. calendar.add(Calendar.MILLISECOND, 500);
  416. calendar.clear(Calendar.MILLISECOND);
  417. }
  418. }
  419. /**
  420. * Get EXCEL date as Java Calendar (with default time zone).
  421. * This is like {@link #getJavaDate(double)} but returns a Calendar object.
  422. * @param date The Excel date.
  423. * @return Java representation of the date, or null if date is not a valid Excel date
  424. */
  425. public static Calendar getJavaCalendar(double date) {
  426. return getJavaCalendar(date, false, null, false);
  427. }
  428. /**
  429. * Get EXCEL date as Java Calendar (with default time zone).
  430. * This is like {@link #getJavaDate(double, boolean)} but returns a Calendar object.
  431. * @param date The Excel date.
  432. * @param use1904windowing true if date uses 1904 windowing,
  433. * or false if using 1900 date windowing.
  434. * @return Java representation of the date, or null if date is not a valid Excel date
  435. */
  436. public static Calendar getJavaCalendar(double date, boolean use1904windowing) {
  437. return getJavaCalendar(date, use1904windowing, null, false);
  438. }
  439. /**
  440. * Get EXCEL date as Java Calendar with UTC time zone.
  441. * This is similar to {@link #getJavaDate(double, boolean)} but returns a
  442. * Calendar object that has UTC as time zone, so no daylight saving hassle.
  443. * @param date The Excel date.
  444. * @param use1904windowing true if date uses 1904 windowing,
  445. * or false if using 1900 date windowing.
  446. * @return Java representation of the date in UTC, or null if date is not a valid Excel date
  447. */
  448. public static Calendar getJavaCalendarUTC(double date, boolean use1904windowing) {
  449. return getJavaCalendar(date, use1904windowing, LocaleUtil.TIMEZONE_UTC, false);
  450. }
  451. /**
  452. * Get EXCEL date as Java Calendar with given time zone.
  453. * @param date The Excel date.
  454. * @param use1904windowing true if date uses 1904 windowing,
  455. * or false if using 1900 date windowing.
  456. * @param timeZone The TimeZone to evaluate the date in
  457. * @return Java representation of the date, or null if date is not a valid Excel date
  458. */
  459. public static Calendar getJavaCalendar(double date, boolean use1904windowing, TimeZone timeZone) {
  460. return getJavaCalendar(date, use1904windowing, timeZone, false);
  461. }
  462. /**
  463. * Get EXCEL date as Java Calendar with given time zone.
  464. * @param date The Excel date.
  465. * @param use1904windowing true if date uses 1904 windowing,
  466. * or false if using 1900 date windowing.
  467. * @param timeZone The TimeZone to evaluate the date in
  468. * @param roundSeconds round to closest second
  469. * @return Java representation of the date, or null if date is not a valid Excel date
  470. */
  471. public static Calendar getJavaCalendar(double date, boolean use1904windowing, TimeZone timeZone, boolean roundSeconds) {
  472. if (!isValidExcelDate(date)) {
  473. return null;
  474. }
  475. int wholeDays = (int)Math.floor(date);
  476. int millisecondsInDay = (int)((date - wholeDays) * DAY_MILLISECONDS + 0.5);
  477. Calendar calendar;
  478. if (timeZone != null) {
  479. calendar = LocaleUtil.getLocaleCalendar(timeZone);
  480. } else {
  481. calendar = LocaleUtil.getLocaleCalendar(); // using default time-zone
  482. }
  483. setCalendar(calendar, wholeDays, millisecondsInDay, use1904windowing, roundSeconds);
  484. return calendar;
  485. }
  486. // variables for performance optimization:
  487. // avoid re-checking DataUtil.isADateFormat(int, String) if a given format
  488. // string represents a date format if the same string is passed multiple times.
  489. // see https://issues.apache.org/bugzilla/show_bug.cgi?id=55611
  490. private static final ThreadLocal<Integer> lastFormatIndex = ThreadLocal.withInitial(() -> -1);
  491. private static final ThreadLocal<String> lastFormatString = new ThreadLocal<>();
  492. private static final ThreadLocal<Boolean> lastCachedResult = new ThreadLocal<>();
  493. private static boolean isCached(String formatString, int formatIndex) {
  494. return formatIndex == lastFormatIndex.get()
  495. && formatString.equals(lastFormatString.get());
  496. }
  497. private static void cache(String formatString, int formatIndex, boolean cached) {
  498. if (formatString == null || "".equals(formatString)) {
  499. lastFormatString.remove();
  500. } else {
  501. lastFormatString.set(formatString);
  502. }
  503. if (formatIndex == -1) {
  504. lastFormatIndex.remove();
  505. } else {
  506. lastFormatIndex.set(formatIndex);
  507. }
  508. lastCachedResult.set(cached);
  509. }
  510. /**
  511. * Given a format ID and its format String, will check to see if the
  512. * format represents a date format or not.
  513. * Firstly, it will check to see if the format ID corresponds to an
  514. * internal excel date format (eg most US date formats)
  515. * If not, it will check to see if the format string only contains
  516. * date formatting characters (ymd-/), which covers most
  517. * non US date formats.
  518. *
  519. * @param numFmt The number format index and string expression, or null if not specified
  520. * @return true if it is a valid date format, false if not or null
  521. * @see #isInternalDateFormat(int)
  522. */
  523. public static boolean isADateFormat(ExcelNumberFormat numFmt) {
  524. if (numFmt == null) {
  525. return false;
  526. }
  527. return isADateFormat(numFmt.getIdx(), numFmt.getFormat());
  528. }
  529. /**
  530. * Given a format ID and its format String, will check to see if the
  531. * format represents a date format or not.
  532. * Firstly, it will check to see if the format ID corresponds to an
  533. * internal excel date format (eg most US date formats)
  534. * If not, it will check to see if the format string only contains
  535. * date formatting characters (ymd-/), which covers most
  536. * non US date formats.
  537. *
  538. * @param formatIndex The index of the format, eg from ExtendedFormatRecord.getFormatIndex
  539. * @param formatString The format string, eg from FormatRecord.getFormatString
  540. * @return true if it is a valid date format, false if not or null
  541. * @see #isInternalDateFormat(int)
  542. */
  543. public static boolean isADateFormat(int formatIndex, String formatString) {
  544. // First up, is this an internal date format?
  545. if(isInternalDateFormat(formatIndex)) {
  546. cache(formatString, formatIndex, true);
  547. return true;
  548. }
  549. // If we didn't get a real string, don't even cache it as we can always find this out quickly
  550. if(formatString == null || formatString.length() == 0) {
  551. return false;
  552. }
  553. // check the cache first
  554. if (isCached(formatString, formatIndex)) {
  555. return lastCachedResult.get();
  556. }
  557. String fs = formatString;
  558. /*if (false) {
  559. // Normalize the format string. The code below is equivalent
  560. // to the following consecutive regexp replacements:
  561. // Translate \- into just -, before matching
  562. fs = fs.replaceAll("\\\\-","-");
  563. // And \, into ,
  564. fs = fs.replaceAll("\\\\,",",");
  565. // And \. into .
  566. fs = fs.replaceAll("\\\\\\.",".");
  567. // And '\ ' into ' '
  568. fs = fs.replaceAll("\\\\ "," ");
  569. // If it end in ;@, that's some crazy dd/mm vs mm/dd
  570. // switching stuff, which we can ignore
  571. fs = fs.replaceAll(";@", "");
  572. // The code above was reworked as suggested in bug 48425:
  573. // simple loop is more efficient than consecutive regexp replacements.
  574. }*/
  575. final int length = fs.length();
  576. StringBuilder sb = new StringBuilder(length);
  577. for (int i = 0; i < length; i++) {
  578. char c = fs.charAt(i);
  579. if (i < length - 1) {
  580. char nc = fs.charAt(i + 1);
  581. if (c == '\\') {
  582. switch (nc) {
  583. case '-':
  584. case ',':
  585. case '.':
  586. case ' ':
  587. case '\\':
  588. // skip current '\' and continue to the next char
  589. continue;
  590. }
  591. } else if (c == ';' && nc == '@') {
  592. i++;
  593. // skip ";@" duplets
  594. continue;
  595. }
  596. }
  597. sb.append(c);
  598. }
  599. fs = sb.toString();
  600. // short-circuit if it indicates elapsed time: [h], [m] or [s]
  601. if(date_ptrn4.matcher(fs).matches()){
  602. cache(formatString, formatIndex, true);
  603. return true;
  604. }
  605. // If it starts with [DBNum1] or [DBNum2] or [DBNum3]
  606. // then it could be a Chinese date
  607. fs = date_ptrn5.matcher(fs).replaceAll("");
  608. // If it starts with [$-...], then could be a date, but
  609. // who knows what that starting bit is all about
  610. fs = date_ptrn1.matcher(fs).replaceAll("");
  611. // If it starts with something like [Black] or [Yellow],
  612. // then it could be a date
  613. fs = date_ptrn2.matcher(fs).replaceAll("");
  614. // You're allowed something like dd/mm/yy;[red]dd/mm/yy
  615. // which would place dates before 1900/1904 in red
  616. // For now, only consider the first one
  617. final int separatorIndex = fs.indexOf(';');
  618. if(0 < separatorIndex && separatorIndex < fs.length()-1) {
  619. fs = fs.substring(0, separatorIndex);
  620. }
  621. // Ensure it has some date letters in it
  622. // (Avoids false positives on the rest of pattern 3)
  623. if (! date_ptrn3a.matcher(fs).find()) {
  624. return false;
  625. }
  626. // If we get here, check it's only made up, in any case, of:
  627. // y m d h s - \ / , . : [ ] T
  628. // optionally followed by AM/PM
  629. boolean result = date_ptrn3b.matcher(fs).matches();
  630. cache(formatString, formatIndex, result);
  631. return result;
  632. }
  633. /**
  634. * Given a format ID this will check whether the format represents
  635. * an internal excel date format or not.
  636. * @see #isADateFormat(int, java.lang.String)
  637. */
  638. public static boolean isInternalDateFormat(int format) {
  639. switch(format) {
  640. // Internal Date Formats as described on page 427 in
  641. // Microsoft Excel Dev's Kit...
  642. case 0x0e:
  643. case 0x0f:
  644. case 0x10:
  645. case 0x11:
  646. case 0x12:
  647. case 0x13:
  648. case 0x14:
  649. case 0x15:
  650. case 0x16:
  651. case 0x2d:
  652. case 0x2e:
  653. case 0x2f:
  654. return true;
  655. }
  656. return false;
  657. }
  658. /**
  659. * Check if a cell contains a date
  660. * Since dates are stored internally in Excel as double values
  661. * we infer it is a date if it is formatted as such.
  662. * @param cell The cell to look at
  663. * @return true if it looks like a date
  664. * @see #isADateFormat(int, String)
  665. * @see #isInternalDateFormat(int)
  666. */
  667. public static boolean isCellDateFormatted(Cell cell) {
  668. return isCellDateFormatted(cell, null);
  669. }
  670. /**
  671. * Check if a cell contains a date
  672. * Since dates are stored internally in Excel as double values
  673. * we infer it is a date if it is formatted as such.
  674. * Format is determined from applicable conditional formatting, if
  675. * any, or cell style.
  676. * @param cell The cell to look at
  677. * @param cfEvaluator if available, or null
  678. * @return true if it looks like a date
  679. * @see #isADateFormat(int, String)
  680. * @see #isInternalDateFormat(int)
  681. */
  682. public static boolean isCellDateFormatted(Cell cell, ConditionalFormattingEvaluator cfEvaluator) {
  683. if (cell == null) {
  684. return false;
  685. }
  686. boolean bDate = false;
  687. double d = cell.getNumericCellValue();
  688. if ( DateUtil.isValidExcelDate(d) ) {
  689. ExcelNumberFormat nf = ExcelNumberFormat.from(cell, cfEvaluator);
  690. if(nf==null) {
  691. return false;
  692. }
  693. bDate = isADateFormat(nf);
  694. }
  695. return bDate;
  696. }
  697. /**
  698. * Check if a cell contains a date, checking only for internal
  699. * excel date formats.
  700. * As Excel stores a great many of its dates in "non-internal"
  701. * date formats, you will not normally want to use this method.
  702. * @see #isADateFormat(int,String)
  703. * @see #isInternalDateFormat(int)
  704. */
  705. public static boolean isCellInternalDateFormatted(Cell cell) {
  706. if (cell == null) {
  707. return false;
  708. }
  709. boolean bDate = false;
  710. double d = cell.getNumericCellValue();
  711. if ( DateUtil.isValidExcelDate(d) ) {
  712. CellStyle style = cell.getCellStyle();
  713. int i = style.getDataFormat();
  714. bDate = isInternalDateFormat(i);
  715. }
  716. return bDate;
  717. }
  718. /**
  719. * Given a double, checks if it is a valid Excel date.
  720. *
  721. * @return true if valid
  722. * @param value the double value
  723. */
  724. public static boolean isValidExcelDate(double value)
  725. {
  726. return (value > -Double.MIN_VALUE);
  727. }
  728. /**
  729. * Given a Calendar, return the number of days since 1900/12/31.
  730. *
  731. * @return days number of days since 1900/12/31
  732. * @param cal the Calendar
  733. * @throws IllegalArgumentException if date is invalid
  734. */
  735. protected static int absoluteDay(Calendar cal, boolean use1904windowing)
  736. {
  737. return absoluteDay(cal.get(Calendar.YEAR), cal.get(Calendar.DAY_OF_YEAR), use1904windowing);
  738. }
  739. /**
  740. * Given a LocalDateTime, return the number of days since 1900/12/31.
  741. *
  742. * @return days number of days since 1900/12/31
  743. * @param date the Date
  744. * @throws IllegalArgumentException if date is invalid
  745. */
  746. protected static int absoluteDay(LocalDateTime date, boolean use1904windowing)
  747. {
  748. return absoluteDay(date.getYear(), date.getDayOfYear(), use1904windowing);
  749. }
  750. /**
  751. * Given a year and day of year, return the number of days since 1900/12/31.
  752. *
  753. * @return days number of days since 1900/12/31
  754. * @param dayOfYear the day of the year
  755. * @param year the year
  756. * @throws IllegalArgumentException if date is invalid
  757. */
  758. private static int absoluteDay(int year, int dayOfYear, boolean use1904windowing) {
  759. return dayOfYear + daysInPriorYears(year, use1904windowing);
  760. }
  761. /**
  762. * Return the number of days in prior years since 1900
  763. *
  764. * @return days number of days in years prior to yr.
  765. * @param yr a year (1900 < yr < 4000)
  766. * @param use1904windowing Should 1900 or 1904 date windowing be used?
  767. * @throws IllegalArgumentException if year is outside of range.
  768. */
  769. static int daysInPriorYears(int yr, boolean use1904windowing)
  770. {
  771. if ((!use1904windowing && yr < 1900) || (use1904windowing && yr < 1904)) {
  772. throw new IllegalArgumentException("'year' must be 1900 or greater");
  773. }
  774. int yr1 = yr - 1;
  775. int leapDays = yr1 / 4 // plus julian leap days in prior years
  776. - yr1 / 100 // minus prior century years
  777. + yr1 / 400 // plus years divisible by 400
  778. - 460; // leap days in previous 1900 years
  779. return 365 * (yr - (use1904windowing ? 1904 : 1900)) + leapDays;
  780. }
  781. // set HH:MM:SS fields of cal to 00:00:00:000
  782. private static Calendar dayStart(final Calendar cal)
  783. {
  784. cal.get(Calendar
  785. .HOUR_OF_DAY); // force recalculation of internal fields
  786. cal.set(Calendar.HOUR_OF_DAY, 0);
  787. cal.set(Calendar.MINUTE, 0);
  788. cal.set(Calendar.SECOND, 0);
  789. cal.set(Calendar.MILLISECOND, 0);
  790. cal.get(Calendar
  791. .HOUR_OF_DAY); // force recalculation of internal fields
  792. return cal;
  793. }
  794. @SuppressWarnings("serial")
  795. private static final class FormatException extends Exception {
  796. public FormatException(String msg) {
  797. super(msg);
  798. }
  799. }
  800. /**
  801. * Converts a string of format "HH:MM" or "HH:MM:SS" to its (Excel) numeric equivalent
  802. *
  803. * @return a double between 0 and 1 representing the fraction of the day
  804. */
  805. public static double convertTime(String timeStr) {
  806. try {
  807. return convertTimeInternal(timeStr);
  808. } catch (FormatException e) {
  809. String msg = "Bad time format '" + timeStr
  810. + "' expected 'HH:MM' or 'HH:MM:SS' - " + e.getMessage();
  811. throw new IllegalArgumentException(msg);
  812. }
  813. }
  814. private static double convertTimeInternal(String timeStr) throws FormatException {
  815. int len = timeStr.length();
  816. if (len < 4 || len > 8) {
  817. throw new FormatException("Bad length");
  818. }
  819. String[] parts = TIME_SEPARATOR_PATTERN.split(timeStr);
  820. String secStr;
  821. switch (parts.length) {
  822. case 2: secStr = "00"; break;
  823. case 3: secStr = parts[2]; break;
  824. default:
  825. throw new FormatException("Expected 2 or 3 fields but got (" + parts.length + ")");
  826. }
  827. String hourStr = parts[0];
  828. String minStr = parts[1];
  829. int hours = parseInt(hourStr, "hour", HOURS_PER_DAY);
  830. int minutes = parseInt(minStr, "minute", MINUTES_PER_HOUR);
  831. int seconds = parseInt(secStr, "second", SECONDS_PER_MINUTE);
  832. double totalSeconds = seconds + (minutes + (hours * 60.0)) * 60.0;
  833. return totalSeconds / (SECONDS_PER_DAY);
  834. }
  835. /**
  836. * Converts a string of format "YYYY/MM/DD" to its (Excel) numeric equivalent
  837. *
  838. * @return a double representing the (integer) number of days since the start of the Excel epoch
  839. */
  840. public static Date parseYYYYMMDDDate(String dateStr) {
  841. try {
  842. return parseYYYYMMDDDateInternal(dateStr);
  843. } catch (FormatException e) {
  844. String msg = "Bad time format " + dateStr
  845. + " expected 'YYYY/MM/DD' - " + e.getMessage();
  846. throw new IllegalArgumentException(msg);
  847. }
  848. }
  849. private static Date parseYYYYMMDDDateInternal(String timeStr) throws FormatException {
  850. if(timeStr.length() != 10) {
  851. throw new FormatException("Bad length");
  852. }
  853. String yearStr = timeStr.substring(0, 4);
  854. String monthStr = timeStr.substring(5, 7);
  855. String dayStr = timeStr.substring(8, 10);
  856. int year = parseInt(yearStr, "year", Short.MIN_VALUE, Short.MAX_VALUE);
  857. int month = parseInt(monthStr, "month", 1, 12);
  858. int day = parseInt(dayStr, "day", 1, 31);
  859. Calendar cal = LocaleUtil.getLocaleCalendar(year, month-1, day);
  860. return cal.getTime();
  861. }
  862. private static int parseInt(String strVal, String fieldName, int rangeMax) throws FormatException {
  863. return parseInt(strVal, fieldName, 0, rangeMax-1);
  864. }
  865. private static int parseInt(String strVal, String fieldName, int lowerLimit, int upperLimit) throws FormatException {
  866. int result;
  867. try {
  868. result = Integer.parseInt(strVal);
  869. } catch (NumberFormatException e) {
  870. throw new FormatException("Bad int format '" + strVal + "' for " + fieldName + " field");
  871. }
  872. if (result < lowerLimit || result > upperLimit) {
  873. throw new FormatException(fieldName + " value (" + result
  874. + ") is outside the allowable range(0.." + upperLimit + ")");
  875. }
  876. return result;
  877. }
  878. public static Double parseDateTime(String str){
  879. TemporalAccessor tmp = dateTimeFormats.parse(str.replaceAll("\\s+", " "));
  880. LocalTime time = tmp.query(TemporalQueries.localTime());
  881. LocalDate date = tmp.query(TemporalQueries.localDate());
  882. if(time == null && date == null) return null;
  883. double tm = 0;
  884. if(date != null) {
  885. Date d = Date.from(date.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
  886. tm = DateUtil.getExcelDate(d);
  887. }
  888. if(time != null) tm += 1.0*time.toSecondOfDay()/SECONDS_PER_DAY;
  889. return tm;
  890. }
  891. }