Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

DateParser.java 4.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  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.util;
  16. import java.text.DateFormatSymbols;
  17. import java.time.LocalDate;
  18. import java.util.ArrayList;
  19. import java.util.Calendar;
  20. import java.util.List;
  21. import java.util.regex.MatchResult;
  22. import java.util.regex.Matcher;
  23. import java.util.regex.Pattern;
  24. import org.apache.poi.ss.formula.eval.ErrorEval;
  25. import org.apache.poi.ss.formula.eval.EvaluationException;
  26. import org.apache.poi.util.LocaleUtil;
  27. /**
  28. * Parser for java dates.
  29. */
  30. public class DateParser {
  31. private DateParser() {
  32. // enforcing singleton
  33. }
  34. private enum Format {
  35. YMD_DASHES("^(\\d{4})-(\\w+)-(\\d{1,2})( .*)?$", "ymd"),
  36. DMY_DASHES("^(\\d{1,2})-(\\w+)-(\\d{4})( .*)?$", "dmy"),
  37. MD_DASHES("^(\\w+)-(\\d{1,2})( .*)?$", "md"),
  38. MDY_SLASHES("^(\\w+)/(\\d{1,2})/(\\d{4})( .*)?$", "mdy"),
  39. YMD_SLASHES("^(\\d{4})/(\\w+)/(\\d{1,2})( .*)?$", "ymd"),
  40. MD_SLASHES("^(\\w+)/(\\d{1,2})( .*)?$", "md");
  41. private Pattern pattern;
  42. private boolean hasYear;
  43. private int yearIndex;
  44. private int monthIndex;
  45. private int dayIndex;
  46. Format(String patternString, String groupOrder) {
  47. this.pattern = Pattern.compile(patternString);
  48. this.hasYear = groupOrder.contains("y");
  49. if (hasYear) {
  50. yearIndex = groupOrder.indexOf("y");
  51. }
  52. monthIndex = groupOrder.indexOf("m");
  53. dayIndex = groupOrder.indexOf("d");
  54. }
  55. }
  56. private static int parseMonth(String monthPart) {
  57. try {
  58. return Integer.parseInt(monthPart);
  59. } catch (NumberFormatException ignored) {
  60. }
  61. String[] months = DateFormatSymbols.getInstance(LocaleUtil.getUserLocale()).getMonths();
  62. for (int month = 0; month < months.length; ++month) {
  63. if (months[month].toLowerCase(LocaleUtil.getUserLocale()).startsWith(monthPart.toLowerCase(LocaleUtil.getUserLocale()))) {
  64. return month + 1;
  65. }
  66. }
  67. return -1;
  68. }
  69. /**
  70. * Parses a date from a string.
  71. *
  72. * @param strVal a string with a date pattern.
  73. * @return a date parsed from argument.
  74. * @throws EvaluationException exception upon parsing.
  75. */
  76. public static LocalDate parseLocalDate(String strVal) throws EvaluationException {
  77. for (Format format : Format.values()) {
  78. Matcher matcher = format.pattern.matcher(strVal);
  79. if (matcher.find()) {
  80. MatchResult matchResult = matcher.toMatchResult();
  81. List<String> groups = new ArrayList<>();
  82. for (int i = 1; i <= matchResult.groupCount(); ++i) {
  83. groups.add(matchResult.group(i));
  84. }
  85. int year = format.hasYear
  86. ? Integer.parseInt(groups.get(format.yearIndex))
  87. : LocalDate.now(LocaleUtil.getUserTimeZone().toZoneId()).getYear();
  88. int month = parseMonth(groups.get(format.monthIndex));
  89. int day = Integer.parseInt(groups.get(format.dayIndex));
  90. return LocalDate.of(year, month, day);
  91. }
  92. }
  93. throw new EvaluationException(ErrorEval.VALUE_INVALID);
  94. }
  95. public static Calendar parseDate(String strVal) throws EvaluationException {
  96. LocalDate date = parseLocalDate(strVal);
  97. return makeDate(date.getYear(), date.getMonthValue(), date.getDayOfMonth());
  98. }
  99. /**
  100. * @param month 1-based
  101. */
  102. private static Calendar makeDate(int year, int month, int day) throws EvaluationException {
  103. if (month < 1 || month > 12) {
  104. throw new EvaluationException(ErrorEval.VALUE_INVALID);
  105. }
  106. Calendar cal = LocaleUtil.getLocaleCalendar(year, month - 1, 1, 0, 0, 0);
  107. if (day < 1 || day > cal.getActualMaximum(Calendar.DAY_OF_MONTH)) {
  108. throw new EvaluationException(ErrorEval.VALUE_INVALID);
  109. }
  110. cal.set(Calendar.DAY_OF_MONTH, day);
  111. return cal;
  112. }
  113. }