/*
 * Copyright (C) The Apache Software Foundation. All rights reserved.
 *
 * This software is published under the terms of the Apache Software License
 * version 1.1, a copy of which has been included with this distribution in
 * the LICENSE file.
 */
package org.apache.log.format;

import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.DateFormat;

/**
 * Format time pattern more human readable.
 * <p>
 * Use subformat of field time to as a SimpleDateFormat formatting string.
 * If no subformat is specified use default dateformat of current locale.
 * </p>
 * <p>You may use any valid SimpleDateFormat time format syntax.
 * </p>
 * <p>For example use 
 * <pre><code>
 *   String format = "%{time:yyyy.MM.dd hh:mm:ss z} " +
 *     "%7.7{priority} [%8.8{category}] (%{context}): " +
 *     "%{message} %{throwable}\\n";
 *   Formatter formatter = new DatePatternFormatter( format );
 *   ....
 * </code></pre>
 * </p>
 * <p> You will get logging lines like:
 * <pre><code>
 *  2001.09.19 01:02:31 GMT+02:00 DEBUG   [junit   ] (): A
 *  2001.09.19 01:02:31 GMT+02:00 INFO    [junit   ] (): B
 *  2001.09.19 01:02:31 GMT+02:00 WARN    [junit   ] (): C
 *  2001.09.19 01:02:31 GMT+02:00 ERROR   [junit   ] (): D
 *  2001.09.19 01:02:31 GMT+02:00 FATAL_E [junit   ] (): E 
 * </code></pre>
 *
 * @see java.text.SimpleDateFormat
 *
 * @author <a href="mailto:bh22351@i-one.at">Bernhard Huber</a>
 *
 */
public class DatePatternFormatter extends PatternFormatter {

    public DatePatternFormatter() {
    }
    
    public DatePatternFormatter( final String pattern ) {
      super( pattern );
    }
    
    /**
     * Utility method to format time.
     * <p>If format is not well formatted 
     * @param time the time
     * @param format ancilliary format parameter - allowed to be null.<br>
     * If format is not null use format as pattern parameter of
     * SimpleDateFormat.<br>
     * If format is not null, and pattern is an invalid SimpleDateFormat pattern,
     * use <code>super.getTime()</code> method.<br>
     * If format is null use DateFormat.getDateTimeInstance() 
     * to obain an DateFormat for formatting time value.
     * @return the formatted string
     */
    protected String getTime( final long time, final String format )
    {
      DateFormat df = null;
      if (format != null) {
        df = new SimpleDateFormat(  format );
      } else {
        df = DateFormat.getDateTimeInstance();
      }
      Date date = new Date( time );
      String result = null;
      try {
        result =  df.format( date );
      } catch (IllegalArgumentException iae) {
        result = super.getTime( time, format );
      }
      return result;
    }
}

