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.

CellDateFormatter.java 8.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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.format;
  16. import java.text.AttributedCharacterIterator;
  17. import java.text.CharacterIterator;
  18. import java.text.DateFormat;
  19. import java.text.SimpleDateFormat;
  20. import java.util.Calendar;
  21. import java.util.Date;
  22. import java.util.Formatter;
  23. import java.util.Locale;
  24. import java.util.regex.Matcher;
  25. import org.apache.poi.util.LocaleUtil;
  26. import org.apache.poi.util.StringUtil;
  27. /**
  28. * Formats a date value.
  29. */
  30. public class CellDateFormatter extends CellFormatter {
  31. private boolean amPmUpper;
  32. private boolean showM;
  33. private boolean showAmPm;
  34. private final DateFormat dateFmt;
  35. private String sFmt;
  36. private final Calendar EXCEL_EPOCH_CAL =
  37. LocaleUtil.getLocaleCalendar(1904, 0, 1);
  38. private static /* final */ CellDateFormatter SIMPLE_DATE;
  39. private class DatePartHandler implements CellFormatPart.PartHandler {
  40. private int mStart = -1;
  41. private int mLen;
  42. private int hStart = -1;
  43. private int hLen;
  44. @Override
  45. public String handlePart(Matcher m, String part, CellFormatType type,
  46. StringBuffer desc) {
  47. int pos = desc.length();
  48. char firstCh = part.charAt(0);
  49. switch (firstCh) {
  50. case 's':
  51. case 'S':
  52. if (mStart >= 0) {
  53. for (int i = 0; i < mLen; i++)
  54. desc.setCharAt(mStart + i, 'm');
  55. mStart = -1;
  56. }
  57. return part.toLowerCase(Locale.ROOT);
  58. case 'h':
  59. case 'H':
  60. mStart = -1;
  61. hStart = pos;
  62. hLen = part.length();
  63. return part.toLowerCase(Locale.ROOT);
  64. case 'd':
  65. case 'D':
  66. mStart = -1;
  67. if (part.length() <= 2)
  68. return part.toLowerCase(Locale.ROOT);
  69. else
  70. return part.toLowerCase(Locale.ROOT).replace('d', 'E');
  71. case 'm':
  72. case 'M':
  73. mStart = pos;
  74. mLen = part.length();
  75. // For 'm' after 'h', output minutes ('m') not month ('M')
  76. if (hStart >= 0)
  77. return part.toLowerCase(Locale.ROOT);
  78. else
  79. return part.toUpperCase(Locale.ROOT);
  80. case 'y':
  81. case 'Y':
  82. mStart = -1;
  83. if (part.length() == 3)
  84. part = "yyyy";
  85. return part.toLowerCase(Locale.ROOT);
  86. case '0':
  87. mStart = -1;
  88. int sLen = part.length();
  89. sFmt = "%0" + (sLen + 2) + "." + sLen + "f";
  90. return part.replace('0', 'S');
  91. case 'a':
  92. case 'A':
  93. case 'p':
  94. case 'P':
  95. if (part.length() > 1) {
  96. // am/pm marker
  97. mStart = -1;
  98. showAmPm = true;
  99. showM = StringUtil.toLowerCase(part.charAt(1)).equals("m");
  100. // For some reason "am/pm" becomes AM or PM, but "a/p" becomes a or p
  101. amPmUpper = showM || StringUtil.isUpperCase(part.charAt(0));
  102. return "a";
  103. }
  104. //noinspection fallthrough
  105. default:
  106. return null;
  107. }
  108. }
  109. public void finish(StringBuffer toAppendTo) {
  110. if (hStart >= 0 && !showAmPm) {
  111. for (int i = 0; i < hLen; i++) {
  112. toAppendTo.setCharAt(hStart + i, 'H');
  113. }
  114. }
  115. }
  116. }
  117. /**
  118. * Creates a new date formatter with the given specification.
  119. *
  120. * @param format The format.
  121. */
  122. public CellDateFormatter(String format) {
  123. this(LocaleUtil.getUserLocale(), format);
  124. }
  125. /**
  126. * Creates a new date formatter with the given specification.
  127. *
  128. * @param locale The locale.
  129. * @param format The format.
  130. */
  131. public CellDateFormatter(Locale locale, String format) {
  132. super(format);
  133. DatePartHandler partHandler = new DatePartHandler();
  134. StringBuffer descBuf = CellFormatPart.parseFormat(format,
  135. CellFormatType.DATE, partHandler);
  136. partHandler.finish(descBuf);
  137. // tweak the format pattern to pass tests on JDK 1.7,
  138. // See https://issues.apache.org/bugzilla/show_bug.cgi?id=53369
  139. String ptrn = descBuf.toString().replaceAll("((y)(?!y))(?<!yy)", "yy");
  140. dateFmt = new SimpleDateFormat(ptrn, locale);
  141. dateFmt.setTimeZone(LocaleUtil.getUserTimeZone());
  142. }
  143. /** {@inheritDoc} */
  144. public synchronized void formatValue(StringBuffer toAppendTo, Object value) {
  145. if (value == null)
  146. value = 0.0;
  147. if (value instanceof Number) {
  148. Number num = (Number) value;
  149. long v = num.longValue();
  150. if (v == 0L) {
  151. value = EXCEL_EPOCH_CAL.getTime();
  152. } else {
  153. Calendar c = (Calendar)EXCEL_EPOCH_CAL.clone();
  154. c.add(Calendar.SECOND, (int)(v / 1000));
  155. c.add(Calendar.MILLISECOND, (int)(v % 1000));
  156. value = c.getTime();
  157. }
  158. }
  159. AttributedCharacterIterator it = dateFmt.formatToCharacterIterator(value);
  160. boolean doneAm = false;
  161. boolean doneMillis = false;
  162. for (char ch = it.first();
  163. ch != CharacterIterator.DONE;
  164. ch = it.next()) {
  165. if (it.getAttribute(DateFormat.Field.MILLISECOND) != null) {
  166. if (!doneMillis) {
  167. Date dateObj = (Date) value;
  168. int pos = toAppendTo.length();
  169. try (Formatter formatter = new Formatter(toAppendTo, Locale.ROOT)) {
  170. long msecs = dateObj.getTime() % 1000;
  171. formatter.format(locale, sFmt, msecs / 1000.0);
  172. }
  173. toAppendTo.delete(pos, pos + 2);
  174. doneMillis = true;
  175. }
  176. } else if (it.getAttribute(DateFormat.Field.AM_PM) != null) {
  177. if (!doneAm) {
  178. if (showAmPm) {
  179. if (amPmUpper) {
  180. toAppendTo.append(StringUtil.toUpperCase(ch));
  181. if (showM)
  182. toAppendTo.append('M');
  183. } else {
  184. toAppendTo.append(StringUtil.toLowerCase(ch));
  185. if (showM)
  186. toAppendTo.append('m');
  187. }
  188. }
  189. doneAm = true;
  190. }
  191. } else {
  192. toAppendTo.append(ch);
  193. }
  194. }
  195. }
  196. /**
  197. * {@inheritDoc}
  198. * <p>
  199. * For a date, this is <tt>"mm/d/y"</tt>.
  200. */
  201. public void simpleValue(StringBuffer toAppendTo, Object value) {
  202. synchronized (CellDateFormatter.class) {
  203. if (SIMPLE_DATE == null || !SIMPLE_DATE.EXCEL_EPOCH_CAL.equals(EXCEL_EPOCH_CAL)) {
  204. SIMPLE_DATE = new CellDateFormatter("mm/d/y");
  205. }
  206. }
  207. SIMPLE_DATE.formatValue(toAppendTo, value);
  208. }
  209. }