/************************************************************************* * * * EJBCA: The OpenSource Certificate Authority * * * * This software is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or any later version. * * * * See terms of license at gnu.org. * * * *************************************************************************/ package org.ejbca.util; import java.text.DateFormat; import java.text.ParseException; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import org.apache.log4j.Logger; /** * Class for encoding and decoding certificate validity and end date. * * @author lars * @version $Id: ValidityDate.java 8159 2009-10-22 10:43:25Z anatom $ */ public class ValidityDate { final private static Logger log = Logger.getLogger(ValidityDate.class); final private static Locale defaultLocale = Locale.getDefault(); final private static int dateStyle = DateFormat.SHORT; final private static int timeStyle = DateFormat.MEDIUM; final private static DateFormat defaultDateFormat = DateFormat.getDateTimeInstance(dateStyle, timeStyle); final private static TimeZone utcTimeZone = TimeZone.getTimeZone("UTC"); static { defaultDateFormat.setTimeZone(utcTimeZone); } /** * This method tries to use a date string to get a {@link java.util.Date} object. * Different ways of getting the date is tried. If one is not working the next is tried: * 1. We just assume that the input is a hex string encoded in seconds since epoch (the Unix time). * 2. The default local is used to try to decode the date in {@link java.text.DateFormat#SHORT} format and time in {@link java.text.DateFormat#MEDIUM} format. Time zone 'UTC' is used. * 3. All available locales are tried until one works. Decoding done the same way as 2 * @param sDate the encoded date. * @return the date decoded from 'sDate'. null if no decoding can be done. */ public static Date getDateFromString(String sDate) { try { final Date date = new Date(Long.parseLong(sDate, 16)*1000); if ( date!=null ) { log.debug("Date as '"+sDate+"' hexadecimal in seconds sinze epoc. Date: "+date); return date; } } catch ( NumberFormatException e) { // just try next } try { final Date date = defaultDateFormat.parse(sDate); if ( date!=null ) { log.debug("Date string '"+sDate+"' with default local '"+defaultLocale.getDisplayName()+"' gives '"+date+"' when decoded." ); return date; } } catch (ParseException e1) { // just try next } log.debug("The default locale '"+defaultLocale.getDisplayName()+"' can not decode the date string '"+sDate+"'."); final Locale[] locales=DateFormat.getAvailableLocales(); for ( int i=0; i