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.

DateFormatConverter.java 7.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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.DateFormat;
  17. import java.text.SimpleDateFormat;
  18. import java.util.ArrayList;
  19. import java.util.HashMap;
  20. import java.util.List;
  21. import java.util.Locale;
  22. import java.util.Map;
  23. import org.apache.logging.log4j.LogManager;
  24. import org.apache.logging.log4j.Logger;
  25. import org.apache.poi.util.LocaleID;
  26. /**
  27. * Convert java DateFormat patterns into Excel custom number formats.
  28. * For example, to format a date in excel using the "dd MMMM, yyyy" pattern and Japanese
  29. * locale, use the following code:
  30. *
  31. * <pre><code>
  32. * // returns "[$-0411]dd MMMM, yyyy;@" where the [$-0411] prefix tells Excel to use the Japanese locale
  33. * String excelFormatPattern = DateFormatConverter.convert(Locale.JAPANESE, "dd MMMM, yyyy");
  34. *
  35. * CellStyle cellStyle = workbook.createCellStyle();
  36. *
  37. * DataFormat poiFormat = workbook.createDataFormat();
  38. * cellStyle.setDataFormat(poiFormat.getFormat(excelFormatPattern));
  39. * cell.setCellValue(new Date());
  40. * cell.setCellStyle(cellStyle); // formats date as '2012\u5e743\u670817\u65e5'
  41. * </code></pre>
  42. *
  43. * TODO Generalise this for all Excel format strings
  44. */
  45. @SuppressWarnings("unused")
  46. public final class DateFormatConverter {
  47. private static final Logger LOG = LogManager.getLogger(DateFormatConverter.class);
  48. private DateFormatConverter() {
  49. }
  50. public static class DateFormatTokenizer {
  51. String format;
  52. int pos;
  53. public DateFormatTokenizer(String format) {
  54. this.format = format;
  55. }
  56. public String getNextToken() {
  57. if( pos >= format.length() ) {
  58. return null;
  59. }
  60. int subStart = pos;
  61. final char curChar = format.charAt(pos);
  62. ++pos;
  63. if( curChar == '\'' ) {
  64. while( ( pos < format.length() ) && ( format.charAt(pos) != '\'' ) ) {
  65. ++pos;
  66. }
  67. if( pos < format.length() ) {
  68. ++pos;
  69. }
  70. } else {
  71. while( ( pos < format.length() ) && ( format.charAt(pos) == curChar ) ) {
  72. ++pos;
  73. }
  74. }
  75. return format.substring(subStart,pos);
  76. }
  77. public static String[] tokenize( String format ) {
  78. List<String> result = new ArrayList<>();
  79. DateFormatTokenizer tokenizer = new DateFormatTokenizer(format);
  80. String token;
  81. while( ( token = tokenizer.getNextToken() ) != null ) {
  82. result.add(token);
  83. }
  84. return result.toArray(new String[0]);
  85. }
  86. @Override
  87. public String toString() {
  88. StringBuilder result = new StringBuilder();
  89. DateFormatTokenizer tokenizer = new DateFormatTokenizer(format);
  90. String token;
  91. while( ( token = tokenizer.getNextToken() ) != null ) {
  92. if( result.length() > 0 ) {
  93. result.append( ", " );
  94. }
  95. result.append("[").append(token).append("]");
  96. }
  97. return result.toString();
  98. }
  99. }
  100. private static Map<String,String> tokenConversions = prepareTokenConversions();
  101. private static Map<String,String> prepareTokenConversions() {
  102. Map<String,String> result = new HashMap<>();
  103. result.put( "EEEE", "dddd" );
  104. result.put( "EEE", "ddd" );
  105. result.put( "EE", "ddd" );
  106. result.put( "E", "d" );
  107. result.put( "Z", "" );
  108. result.put( "z", "" );
  109. result.put( "a", "am/pm" );
  110. result.put( "A", "AM/PM" );
  111. result.put( "K", "H" );
  112. result.put( "KK", "HH" );
  113. result.put( "k", "h" );
  114. result.put( "kk", "hh" );
  115. result.put( "S", "0" );
  116. result.put( "SS", "00" );
  117. result.put( "SSS", "000" );
  118. result.put( "y", "yyyy" );
  119. return result;
  120. }
  121. public static String getPrefixForLocale( Locale locale ) {
  122. final String languageTag = locale.toLanguageTag();
  123. if (Locale.ROOT.equals(locale) || "".equals(languageTag)) {
  124. // JDK 8 adds an empty locale-string, see also https://issues.apache.org/jira/browse/LANG-941
  125. return "";
  126. }
  127. LocaleID loc = LocaleID.lookupByLanguageTag(languageTag);
  128. if (loc == null) {
  129. String cmpTag = (languageTag.indexOf('_') > -1) ? languageTag.replace('_', '-') : languageTag;
  130. int idx = languageTag.length();
  131. while (loc == null && (idx = cmpTag.lastIndexOf('-', idx - 1)) > 0) {
  132. loc = LocaleID.lookupByLanguageTag(languageTag.substring(0, idx));
  133. }
  134. }
  135. if (loc == null) {
  136. LOG.atError().log("Unable to find prefix for Locale '{}' or its parent locales.", languageTag);
  137. return "";
  138. }
  139. return String.format(Locale.ROOT, "[$-%04X]", loc.getLcid());
  140. }
  141. public static String convert( Locale locale, DateFormat df ) {
  142. String ptrn = ((SimpleDateFormat)df).toPattern();
  143. return convert(locale, ptrn);
  144. }
  145. public static String convert( Locale locale, String format ) {
  146. StringBuilder result = new StringBuilder();
  147. result.append(getPrefixForLocale(locale));
  148. DateFormatTokenizer tokenizer = new DateFormatTokenizer(format);
  149. String token;
  150. while( ( token = tokenizer.getNextToken() ) != null ) {
  151. if( token.startsWith("'") ) {
  152. result.append( token.replace('\'', '"') );
  153. } else if( ! Character.isLetter( token.charAt( 0 ) ) ) {
  154. result.append( token );
  155. } else {
  156. // It's a code, translate it if necessary
  157. String mappedToken = tokenConversions.get(token);
  158. result.append( mappedToken == null ? token : mappedToken );
  159. }
  160. }
  161. result.append(";@");
  162. return result.toString().trim();
  163. }
  164. public static String getJavaDatePattern(int style, Locale locale) {
  165. DateFormat df = DateFormat.getDateInstance(style, locale);
  166. if( df instanceof SimpleDateFormat ) {
  167. return ((SimpleDateFormat)df).toPattern();
  168. } else {
  169. switch( style ) {
  170. case DateFormat.SHORT:
  171. return "d/MM/yy";
  172. case DateFormat.LONG:
  173. return "MMMM d, yyyy";
  174. case DateFormat.FULL:
  175. return "dddd, MMMM d, yyyy";
  176. default:
  177. case DateFormat.MEDIUM:
  178. return "MMM d, yyyy";
  179. }
  180. }
  181. }
  182. public static String getJavaTimePattern(int style, Locale locale) {
  183. DateFormat df = DateFormat.getTimeInstance(style, locale);
  184. if( df instanceof SimpleDateFormat ) {
  185. return ((SimpleDateFormat)df).toPattern();
  186. } else {
  187. switch( style ) {
  188. case DateFormat.SHORT:
  189. return "h:mm a";
  190. default:
  191. case DateFormat.MEDIUM:
  192. case DateFormat.LONG:
  193. case DateFormat.FULL:
  194. return "h:mm:ss a";
  195. }
  196. }
  197. }
  198. public static String getJavaDateTimePattern(int style, Locale locale) {
  199. DateFormat df = DateFormat.getDateTimeInstance(style, style, locale);
  200. if( df instanceof SimpleDateFormat ) {
  201. return ((SimpleDateFormat)df).toPattern();
  202. } else {
  203. switch( style ) {
  204. case DateFormat.SHORT:
  205. return "M/d/yy h:mm a";
  206. case DateFormat.LONG:
  207. return "MMMM d, yyyy h:mm:ss a";
  208. case DateFormat.FULL:
  209. return "dddd, MMMM d, yyyy h:mm:ss a";
  210. default:
  211. case DateFormat.MEDIUM:
  212. return "MMM d, yyyy h:mm:ss a";
  213. }
  214. }
  215. }
  216. }