/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package org.apache.poi.ss.usermodel; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.regex.Pattern; /** * Contains methods for dealing with Excel dates. * * @author Michael Harhen * @author Glen Stampoultzis (glens at apache.org) * @author Dan Sherman (dsherman at isisph.com) * @author Hack Kampbjorn (hak at 2mba.dk) * @author Alex Jacoby (ajacoby at gmail.com) * @author Pavel Krupets (pkrupets at palmtreebusiness dot com) */ public class DateUtil { protected DateUtil() { // no instances of this class } private static final int SECONDS_PER_MINUTE = 60; private static final int MINUTES_PER_HOUR = 60; private static final int HOURS_PER_DAY = 24; private static final int SECONDS_PER_DAY = (HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE); private static final long DAY_MILLISECONDS = SECONDS_PER_DAY * 1000L; /** * The following patterns are used in {@link #isADateFormat(int, String)} */ private static final Pattern date_ptrn1 = Pattern.compile("^\\[\\$\\-.*?\\]"); private static final Pattern date_ptrn2 = Pattern.compile("^\\[[a-zA-Z]+\\]"); private static final Pattern date_ptrn3 = Pattern.compile("^[yYmMdDhHsS\\-/,. :\"\\\\]+0?[ampAMP/]*$"); /** * Given an Excel date with either 1900 or 1904 date windowing, * converts it to a java.util.Date. * * NOTE: If the default <code>TimeZone</code> in Java uses Daylight * Saving Time then the conversion back to an Excel date may not give * the same value, that is the comparison * <CODE>excelDate == getExcelDate(getJavaDate(excelDate,false))</CODE> * is not always true. For example if default timezone is * <code>Europe/Copenhagen</code>, on 2004-03-28 the minute after * 01:59 CET is 03:00 CEST, if the excel date represents a time between * 02:00 and 03:00 then it is converted to past 03:00 summer time * * @param date The Excel date. * @param use1904windowing true if date uses 1904 windowing, * or false if using 1900 date windowing. * @return Java representation of the date, or null if date is not a valid Excel date * @see java.util.TimeZone */ public static Date getJavaDate(double date, boolean use1904windowing) { if (!isValidExcelDate(date)) { return null; } int wholeDays = (int)Math.floor(date); int millisecondsInDay = (int)((date - wholeDays) * DAY_MILLISECONDS + 0.5); Calendar calendar = new GregorianCalendar(); // using default time-zone setCalendar(calendar, wholeDays, millisecondsInDay, use1904windowing); return calendar.getTime(); } public static void setCalendar(Calendar calendar, int wholeDays, int millisecondsInDay, boolean use1904windowing) { int startYear = 1900; int dayAdjust = -1; // Excel thinks 2/29/1900 is a valid date, which it isn't if (use1904windowing) { startYear = 1904; dayAdjust = 1; // 1904 date windowing uses 1/2/1904 as the first day } else if (wholeDays < 61) { // Date is prior to 3/1/1900, so adjust because Excel thinks 2/29/1900 exists // If Excel date == 2/29/1900, will become 3/1/1900 in Java representation dayAdjust = 0; } calendar.set(startYear,0, wholeDays + dayAdjust, 0, 0, 0); calendar.set(GregorianCalendar.MILLISECOND, millisecondsInDay); } /** * Given a format ID and its format String, will check to see if the * format represents a date format or not. * Firstly, it will check to see if the format ID corresponds to an * internal excel date format (eg most US date formats) * If not, it will check to see if the format string only contains * date formatting characters (ymd-/), which covers most * non US date formats. * * @param formatIndex The index of the format, eg from ExtendedFormatRecord.getFormatIndex * @param formatString The format string, eg from FormatRecord.getFormatString * @see #isInternalDateFormat(int) */ public static boolean isADateFormat(int formatIndex, String formatString) { // First up, is this an internal date format? if(isInternalDateFormat(formatIndex)) { return true; } // If we didn't get a real string, it can't be if(formatString == null || formatString.length() == 0) { return false; } String fs = formatString; StringBuilder sb = new StringBuilder(fs.length()); for (int i = 0; i < fs.length(); i++) { char c = fs.charAt(i); if (i < fs.length() - 1) { char nc = fs.charAt(i + 1); if (c == '\\') { switch (nc) { case '-': case ',': case '.': case ' ': case '\\': // skip current '\' and continue to the next char continue; } } else if (c == ';' && nc == '@') { i++; // skip ";@" duplets continue; } } sb.append(c); } fs = sb.toString(); // If it starts with [$-...], then could be a date, but // who knows what that starting bit is all about fs = date_ptrn1.matcher(fs).replaceAll(""); // If it starts with something like [Black] or [Yellow], // then it could be a date fs = date_ptrn2.matcher(fs).replaceAll(""); // You're allowed something like dd/mm/yy;[red]dd/mm/yy // which would place dates before 1900/1904 in red // For now, only consider the first one if(fs.indexOf(';') > 0 && fs.indexOf(';') < fs.length()-1) { fs = fs.substring(0, fs.indexOf(';')); } // Otherwise, check it's only made up, in any case, of: // y m d h s - \ / , . : // optionally followed by AM/PM return date_ptrn3.matcher(fs).matches(); } /** * Given a format ID this will check whether the format represents * an internal excel date format or not. * @see #isADateFormat(int, java.lang.String) */ public static boolean isInternalDateFormat(int format) { switch(format) { // Internal Date Formats as described on page 427 in // Microsoft Excel Dev's Kit... case 0x0e: case 0x0f: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x2d: case 0x2e: case 0x2f: return true; } return false; } /** * Check if a cell contains a date * Since dates are stored internally in Excel as double values * we infer it is a date if it is formatted as such. * @see #isADateFormat(int, String) * @see #isInternalDateFormat(int) */ public static boolean isCellDateFormatted(Cell cell) { if (cell == null) return false; boolean bDate = false; double d = cell.getNumericCellValue(); if ( DateUtil.isValidExcelDate(d) ) { CellStyle style = cell.getCellStyle(); if(style==null) return false; int i = style.getDataFormat(); String f = style.getDataFormatString(); bDate = isADateFormat(i, f); } return bDate; } /** * Given a double, checks if it is a valid Excel date. * * @return true if valid * @param value the double value */ public static boolean isValidExcelDate(double value) { return (value > -Double.MIN_VALUE); } }