Java Tutorial/Data Type/Date Format

Материал из Java эксперт
Версия от 15:26, 31 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Содержание

A formatter that formats dates to show the elapsed time relative to some base date.

/* 
 * JFreeChart : a free chart library for the Java(tm) platform
 * 
 *
 * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors.
 *
 * Project Info:  http://www.jfree.org/jfreechart/index.html
 *
 * This library 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
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
 * in the United States and other countries.]
 *
 * -----------------------
 * RelativeDateFormat.java
 * -----------------------
 * (C) Copyright 2006-2008, by Object Refinery Limited and Contributors.
 *
 * Original Author:  David Gilbert (for Object Refinery Limited);
 * Contributor(s):   Michael Siemer;
 *
 * Changes:
 * --------
 * 01-Nov-2006 : Version 1 (DG);
 * 23-Nov-2006 : Added argument checks, updated equals(), added clone() and
 *               hashCode() (DG);
 * 15-Feb-2008 : Applied patch 1873328 by Michael Siemer, with minor
 *               modifications (DG);
 * 01-Sep-2008 : Added new fields for hour and minute formatting, based on
 *               patch 2033092 (DG);
 *
 */

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
/**
 * A formatter that formats dates to show the elapsed time relative to some
 * base date.
 *
 * @since 1.0.3
 */
public class RelativeDateFormat extends DateFormat {
    /** The base milliseconds for the elapsed time calculation. */
    private long baseMillis;
    /**
     * A flag that controls whether or not a zero day count is displayed.
     */
    private boolean showZeroDays;
    /**
     * A flag that controls whether or not a zero hour count is displayed.
     *
     * @since 1.0.10
     */
    private boolean showZeroHours;
    /**
     * A formatter for the day count (most likely not critical until the
     * day count exceeds 999).
     */
    private NumberFormat dayFormatter;
    /**
     * A prefix prepended to the start of the format if the relative date is
     * positive.
     *
     * @since 1.0.10
     */
    private String positivePrefix;
    /**
     * A string appended after the day count.
     */
    private String daySuffix;
    /**
     * A formatter for the hours.
     *
     * @since 1.0.11
     */
    private NumberFormat hourFormatter;
    /**
     * A string appended after the hours.
     */
    private String hourSuffix;
    /**
     * A formatter for the minutes.
     *
     * @since 1.0.11
     */
    private NumberFormat minuteFormatter;
    /**
     * A string appended after the minutes.
     */
    private String minuteSuffix;
    /**
     * A formatter for the seconds (and milliseconds).
     */
    private NumberFormat secondFormatter;
    /**
     * A string appended after the seconds.
     */
    private String secondSuffix;
    /**
     * A constant for the number of milliseconds in one hour.
     */
    private static long MILLISECONDS_IN_ONE_HOUR = 60 * 60 * 1000L;
    /**
     * A constant for the number of milliseconds in one day.
     */
    private static long MILLISECONDS_IN_ONE_DAY = 24 * MILLISECONDS_IN_ONE_HOUR;
    /**
     * Creates a new instance with base milliseconds set to zero.
     */
    public RelativeDateFormat() {
        this(0L);
    }
    /**
     * Creates a new instance.
     *
     * @param time  the date/time (<code>null</code> not permitted).
     */
    public RelativeDateFormat(Date time) {
        this(time.getTime());
    }
    /**
     * Creates a new instance.
     *
     * @param baseMillis  the time zone (<code>null</code> not permitted).
     */
    public RelativeDateFormat(long baseMillis) {
        super();
        this.baseMillis = baseMillis;
        this.showZeroDays = false;
        this.showZeroHours = true;
        this.positivePrefix = "";
        this.dayFormatter = NumberFormat.getNumberInstance();
        this.daySuffix = "d";
        this.hourFormatter = NumberFormat.getNumberInstance();
        this.hourSuffix = "h";
        this.minuteFormatter = NumberFormat.getNumberInstance();
        this.minuteSuffix = "m";
        this.secondFormatter = NumberFormat.getNumberInstance();
        this.secondFormatter.setMaximumFractionDigits(3);
        this.secondFormatter.setMinimumFractionDigits(3);
        this.secondSuffix = "s";
        // we don"t use the calendar or numberFormat fields, but equals(Object)
        // is failing without them being non-null
        this.calendar = new GregorianCalendar();
        this.numberFormat = new DecimalFormat("0");
    }
    /**
     * Returns the base date/time used to calculate the elapsed time for
     * display.
     *
     * @return The base date/time in milliseconds since 1-Jan-1970.
     *
     * @see #setBaseMillis(long)
     */
    public long getBaseMillis() {
        return this.baseMillis;
    }
    /**
     * Sets the base date/time used to calculate the elapsed time for display.
     * This should be specified in milliseconds using the same encoding as
     * <code>java.util.Date</code>.
     *
     * @param baseMillis  the base date/time in milliseconds.
     *
     * @see #getBaseMillis()
     */
    public void setBaseMillis(long baseMillis) {
        this.baseMillis = baseMillis;
    }
    /**
     * Returns the flag that controls whether or not zero day counts are
     * shown in the formatted output.
     *
     * @return The flag.
     *
     * @see #setShowZeroDays(boolean)
     */
    public boolean getShowZeroDays() {
        return this.showZeroDays;
    }
    /**
     * Sets the flag that controls whether or not zero day counts are shown
     * in the formatted output.
     *
     * @param show  the flag.
     *
     * @see #getShowZeroDays()
     */
    public void setShowZeroDays(boolean show) {
        this.showZeroDays = show;
    }
    /**
     * Returns the flag that controls whether or not zero hour counts are
     * shown in the formatted output.
     *
     * @return The flag.
     *
     * @see #setShowZeroHours(boolean)
     *
     * @since 1.0.10
     */
    public boolean getShowZeroHours() {
        return this.showZeroHours;
    }
    /**
     * Sets the flag that controls whether or not zero hour counts are shown
     * in the formatted output.
     *
     * @param show  the flag.
     *
     * @see #getShowZeroHours()
     *
     * @since 1.0.10
     */
    public void setShowZeroHours(boolean show) {
        this.showZeroHours = show;
    }
    /**
     * Returns the string that is prepended to the format if the relative time
     * is positive.
     *
     * @return The string (never <code>null</code>).
     *
     * @see #setPositivePrefix(String)
     *
     * @since 1.0.10
     */
    public String getPositivePrefix() {
        return this.positivePrefix;
    }
    /**
     * Sets the string that is prepended to the format if the relative time is
     * positive.
     *
     * @param prefix  the prefix (<code>null</code> not permitted).
     *
     * @see #getPositivePrefix()
     *
     * @since 1.0.10
     */
    public void setPositivePrefix(String prefix) {
        if (prefix == null) {
            throw new IllegalArgumentException("Null "prefix" argument.");
        }
        this.positivePrefix = prefix;
    }
    /**
     * Sets the formatter for the days.
     *
     * @param formatter  the formatter (<code>null</code> not permitted).
     *
     * @since 1.0.11
     */
    public void setDayFormatter(NumberFormat formatter) {
        if (formatter == null) {
            throw new IllegalArgumentException("Null "formatter" argument.");
        }
        this.dayFormatter = formatter;
    }
    /**
     * Returns the string that is appended to the day count.
     *
     * @return The string.
     *
     * @see #setDaySuffix(String)
     */
    public String getDaySuffix() {
        return this.daySuffix;
    }
    /**
     * Sets the string that is appended to the day count.
     *
     * @param suffix  the suffix (<code>null</code> not permitted).
     *
     * @see #getDaySuffix()
     */
    public void setDaySuffix(String suffix) {
        if (suffix == null) {
            throw new IllegalArgumentException("Null "suffix" argument.");
        }
        this.daySuffix = suffix;
    }
    /**
     * Sets the formatter for the hours.
     *
     * @param formatter  the formatter (<code>null</code> not permitted).
     *
     * @since 1.0.11
     */
    public void setHourFormatter(NumberFormat formatter) {
        if (formatter == null) {
            throw new IllegalArgumentException("Null "formatter" argument.");
        }
        this.hourFormatter = formatter;
    }
    /**
     * Returns the string that is appended to the hour count.
     *
     * @return The string.
     *
     * @see #setHourSuffix(String)
     */
    public String getHourSuffix() {
        return this.hourSuffix;
    }
    /**
     * Sets the string that is appended to the hour count.
     *
     * @param suffix  the suffix (<code>null</code> not permitted).
     *
     * @see #getHourSuffix()
     */
    public void setHourSuffix(String suffix) {
        if (suffix == null) {
            throw new IllegalArgumentException("Null "suffix" argument.");
        }
        this.hourSuffix = suffix;
    }
    /**
     * Sets the formatter for the minutes.
     *
     * @param formatter  the formatter (<code>null</code> not permitted).
     *
     * @since 1.0.11
     */
    public void setMinuteFormatter(NumberFormat formatter) {
        if (formatter == null) {
            throw new IllegalArgumentException("Null "formatter" argument.");
        }
        this.minuteFormatter = formatter;
    }
    /**
     * Returns the string that is appended to the minute count.
     *
     * @return The string.
     *
     * @see #setMinuteSuffix(String)
     */
    public String getMinuteSuffix() {
        return this.minuteSuffix;
    }
    /**
     * Sets the string that is appended to the minute count.
     *
     * @param suffix  the suffix (<code>null</code> not permitted).
     *
     * @see #getMinuteSuffix()
     */
    public void setMinuteSuffix(String suffix) {
        if (suffix == null) {
            throw new IllegalArgumentException("Null "suffix" argument.");
        }
        this.minuteSuffix = suffix;
    }
    /**
     * Returns the string that is appended to the second count.
     *
     * @return The string.
     *
     * @see #setSecondSuffix(String)
     */
    public String getSecondSuffix() {
        return this.secondSuffix;
    }
    /**
     * Sets the string that is appended to the second count.
     *
     * @param suffix  the suffix (<code>null</code> not permitted).
     *
     * @see #getSecondSuffix()
     */
    public void setSecondSuffix(String suffix) {
        if (suffix == null) {
            throw new IllegalArgumentException("Null "suffix" argument.");
        }
        this.secondSuffix = suffix;
    }
    /**
     * Sets the formatter for the seconds and milliseconds.
     *
     * @param formatter  the formatter (<code>null</code> not permitted).
     */
    public void setSecondFormatter(NumberFormat formatter) {
        if (formatter == null) {
            throw new IllegalArgumentException("Null "formatter" argument.");
        }
        this.secondFormatter = formatter;
    }
    /**
     * Formats the given date as the amount of elapsed time (relative to the
     * base date specified in the constructor).
     *
     * @param date  the date.
     * @param toAppendTo  the string buffer.
     * @param fieldPosition  the field position.
     *
     * @return The formatted date.
     */
    public StringBuffer format(Date date, StringBuffer toAppendTo,
                               FieldPosition fieldPosition) {
        long currentMillis = date.getTime();
        long elapsed = currentMillis - this.baseMillis;
        String signPrefix;
        if (elapsed < 0) {
            elapsed *= -1L;
            signPrefix = "-";
        }
        else {
            signPrefix = this.positivePrefix;
        }
        long days = elapsed / MILLISECONDS_IN_ONE_DAY;
        elapsed = elapsed - (days * MILLISECONDS_IN_ONE_DAY);
        long hours = elapsed / MILLISECONDS_IN_ONE_HOUR;
        elapsed = elapsed - (hours * MILLISECONDS_IN_ONE_HOUR);
        long minutes = elapsed / 60000L;
        elapsed = elapsed - (minutes * 60000L);
        double seconds = elapsed / 1000.0;
        toAppendTo.append(signPrefix);
        if (days != 0 || this.showZeroDays) {
            toAppendTo.append(this.dayFormatter.format(days) + getDaySuffix());
        }
        if (hours != 0 || this.showZeroHours) {
            toAppendTo.append(this.hourFormatter.format(hours)
                    + getHourSuffix());
        }
        toAppendTo.append(this.minuteFormatter.format(minutes)
                + getMinuteSuffix());
        toAppendTo.append(this.secondFormatter.format(seconds)
                + getSecondSuffix());
        return toAppendTo;
    }
    /**
     * Parses the given string (not implemented).
     *
     * @param source  the date string.
     * @param pos  the parse position.
     *
     * @return <code>null</code>, as this method has not been implemented.
     */
    public Date parse(String source, ParsePosition pos) {
        return null;
    }
    /**
     * Tests this formatter for equality with an arbitrary object.
     *
     * @param obj  the object (<code>null</code> permitted).
     *
     * @return A boolean.
     */
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof RelativeDateFormat)) {
            return false;
        }
        if (!super.equals(obj)) {
            return false;
        }
        RelativeDateFormat that = (RelativeDateFormat) obj;
        if (this.baseMillis != that.baseMillis) {
            return false;
        }
        if (this.showZeroDays != that.showZeroDays) {
            return false;
        }
        if (this.showZeroHours != that.showZeroHours) {
            return false;
        }
        if (!this.positivePrefix.equals(that.positivePrefix)) {
            return false;
        }
        if (!this.daySuffix.equals(that.daySuffix)) {
            return false;
        }
        if (!this.hourSuffix.equals(that.hourSuffix)) {
            return false;
        }
        if (!this.minuteSuffix.equals(that.minuteSuffix)) {
            return false;
        }
        if (!this.secondSuffix.equals(that.secondSuffix)) {
            return false;
        }
        if (!this.dayFormatter.equals(that.dayFormatter)) {
            return false;
        }
        if (!this.hourFormatter.equals(that.hourFormatter)) {
            return false;
        }
        if (!this.minuteFormatter.equals(that.minuteFormatter)) {
            return false;
        }
        if (!this.secondFormatter.equals(that.secondFormatter)) {
            return false;
        }
        return true;
    }
    /**
     * Returns a hash code for this instance.
     *
     * @return A hash code.
     */
    public int hashCode() {
        int result = 193;
        result = 37 * result
                + (int) (this.baseMillis ^ (this.baseMillis >>> 32));
        result = 37 * result + this.positivePrefix.hashCode();
        result = 37 * result + this.daySuffix.hashCode();
        result = 37 * result + this.hourSuffix.hashCode();
        result = 37 * result + this.minuteSuffix.hashCode();
        result = 37 * result + this.secondSuffix.hashCode();
        result = 37 * result + this.secondFormatter.hashCode();
        return result;
    }
    /**
     * Returns a clone of this instance.
     *
     * @return A clone.
     */
    public Object clone() {
        RelativeDateFormat clone = (RelativeDateFormat) super.clone();
        clone.dayFormatter = (NumberFormat) this.dayFormatter.clone();
        clone.secondFormatter = (NumberFormat) this.secondFormatter.clone();
        return clone;
    }
    /**
     * Some test code.
     *
     * @param args  ignored.
     */
    public static void main(String[] args) {
        GregorianCalendar c0 = new GregorianCalendar(2006, 10, 1, 0, 0, 0);
        GregorianCalendar c1 = new GregorianCalendar(2006, 10, 1, 11, 37, 43);
        c1.set(Calendar.MILLISECOND, 123);
        System.out.println("Default: ");
        RelativeDateFormat rdf = new RelativeDateFormat(c0.getTime().getTime());
        System.out.println(rdf.format(c1.getTime()));
        System.out.println();
        System.out.println("Hide milliseconds: ");
        rdf.setSecondFormatter(new DecimalFormat("0"));
        System.out.println(rdf.format(c1.getTime()));
        System.out.println();
        System.out.println("Show zero day output: ");
        rdf.setShowZeroDays(true);
        System.out.println(rdf.format(c1.getTime()));
        System.out.println();
        System.out.println("Alternative suffixes: ");
        rdf.setShowZeroDays(false);
        rdf.setDaySuffix(":");
        rdf.setHourSuffix(":");
        rdf.setMinuteSuffix(":");
        rdf.setSecondSuffix("");
        System.out.println(rdf.format(c1.getTime()));
        System.out.println();
    }
}





Change date formatting symbols

import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.util.Date;
public class Main {
  public static void main(String[] args) {
    String[] newMonths = { "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT",
        "NOV", "DEC" };
    String[] newShortMonths = { "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep",
        "oct", "nov", "dec" };
    String[] newWeekdays = { "", "Monday", "Tuesday", "Webnesday", "Thursday", "Friday",
        "Saturaday", "Sunday" };
    String[] shortWeekdays = { "", "monday", "tuesday", "webnesday", "thursday", "friday",
        "saturaday", "sunday" };
    DateFormatSymbols symbols = new DateFormatSymbols();
    symbols.setMonths(newMonths);
    symbols.setShortMonths(newShortMonths);
    symbols.setWeekdays(newWeekdays);
    symbols.setShortWeekdays(shortWeekdays);
    DateFormat format = new SimpleDateFormat("dd MMMM yyyy", symbols);
    System.out.println(format.format(new Date()));
    format = new SimpleDateFormat("dd MMM yyyy", symbols);
    System.out.println(format.format(new Date()));
    format = new SimpleDateFormat("EEEE, dd MMM yyyy", symbols);
    System.out.println(format.format(new Date()));
    format = new SimpleDateFormat("E, dd MMM yyyy", symbols);
    System.out.println(format.format(new Date()));
  }
}





Date and time with day and month fully spelled-out

import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
  public static void main(String[] argv) throws Exception {
    Date date = new Date();
    SimpleDateFormat simpDate;
    simpDate = new SimpleDateFormat("EEEE MMMMM dd yyyy kk:mm:ss");
    System.out.println(simpDate.format(date));
  }
}





Date and time with month

import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
  public static void main(String[] argv) throws Exception {
    Date date = new Date();
    SimpleDateFormat simpDate;
    simpDate = new SimpleDateFormat("dd MMM yyyy hh:mm:ss a");
    System.out.println(simpDate.format(date));
  }
}





Date Era change

import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ChangeEra {
  public static void main(String s[]) {
    SimpleDateFormat sdf = new SimpleDateFormat();
    DateFormatSymbols dfs = sdf.getDateFormatSymbols();
    String era[] = { "BCE", "CE" };
    dfs.setEras(era);
    sdf.setDateFormatSymbols(dfs);
    sdf.applyPattern("MMMM d yyyy G");
    System.out.println(sdf.format(new Date()));
  }
}





DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.MEDIUM)

import java.text.DateFormat;
import java.util.Calendar;
public class CalendarManipulation {
  public static void main(String s[]) {
    Calendar cal = Calendar.getInstance();
    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.MEDIUM);
    System.out.println(df.format(cal.getTime()));
    cal.add(Calendar.AM_PM, 1);
    System.out.println(df.format(cal.getTime()));
  }
}





Date Format with SimpleDateFormat

import java.text.SimpleDateFormat;
import java.util.Date;
class DateFormatApp {
  public static void main(String args[]) {
    String pattern = ""The year is "";
    pattern += "yyyy GG";
    pattern += "".\nThe month is "";
    pattern += "MMMMMMMMM";
    pattern += "".\nIt is "";
    pattern += "hh";
    pattern += "" o""clock "";
    pattern += "a, zzzz";
    pattern += ""."";
    SimpleDateFormat format = new SimpleDateFormat(pattern);
    String formattedDate = format.format(new Date());
    System.out.println(formattedDate);
  }
}





Date Parsing and Formatting with DateFormat

  1. DateFormat supports styles or patterns.
  2. There are four styles you can format a Date object to.
  3. Each style is represented by an int value.
  4. The four int fields that represent the styles are:

ValueExampleDateFormat.SHORT.For example, 12/2/05DateFormat.MEDIUM.For example, Dec 2, 2005.DateFormat.LONG.For example, December 2, 2005DateFormat.FULL.For example, Friday, December 2, 2005



import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
public class MainClass {
  public static void main(String[] args) {
    DateFormat shortDf = DateFormat.getDateInstance(DateFormat.SHORT);
    DateFormat mediumDf = DateFormat.getDateInstance(DateFormat.MEDIUM);
    DateFormat longDf = DateFormat.getDateInstance(DateFormat.LONG);
    DateFormat fullDf = DateFormat.getDateInstance(DateFormat.FULL);
    System.out.println(shortDf.format(new Date()));
    System.out.println(mediumDf.format(new Date()));
    System.out.println(longDf.format(new Date()));
    System.out.println(fullDf.format(new Date()));
    // parsing
    try {
      Date date = shortDf.parse("12/12/2006");
    } catch (ParseException e) {
    }
  }
}



1/26/07
Jan 26, 2007
January 26, 2007
Friday, January 26, 2007


Demonstrate date formats with different DateFormat constants

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
public class DateFormatDemo {
  public static void main(String args[]) {
    Date date = new Date();
    DateFormat df;
    df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.JAPAN);
    System.out.println("Japan: " + df.format(date));
    df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.KOREA);
    System.out.println("Korea: " + df.format(date));
    df = DateFormat.getDateInstance(DateFormat.LONG, Locale.UK);
    System.out.println("United Kingdom: " + df.format(date));
    df = DateFormat.getDateInstance(DateFormat.FULL, Locale.US);
    System.out.println("United States: " + df.format(date));
  }
}





Demonstrate time formats.

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
public class TimeFormatDemo {
  public static void main(String args[]) {
    Date date = new Date();
    DateFormat df;
    df = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.JAPAN);
    System.out.println("Japan: " + df.format(date));
    df = DateFormat.getTimeInstance(DateFormat.LONG, Locale.UK);
    System.out.println("United Kingdom: " + df.format(date));
    df = DateFormat.getTimeInstance(DateFormat.FULL, Locale.CANADA);
    System.out.println("Canada: " + df.format(date));
  }
}





Display date with a short day and month name

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
  public static void main(String[] argv) throws Exception {
    Format formatter = new SimpleDateFormat("EEE, dd MMM yyyy");
    String today = formatter.format(new Date());
    System.out.println("Today : " + today);
  }
}





Display date with day name in a short format

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
  public static void main(String[] argv) throws Exception {
    Format formatter = new SimpleDateFormat("EEE, dd/MM/yyyy");
    String today = formatter.format(new Date());
    System.out.println("Today : " + today);
  }
}





Express a duration in term of HH:MM:SS

import java.util.Calendar;
public class Main {
  public static void main(String args[]) {
    Calendar cal1 = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();
    cal2.add(Calendar.HOUR, 2);
    cal2.add(Calendar.MINUTE, 42);
    cal2.add(Calendar.SECOND, 12);
    long secs = (cal2.getTimeInMillis() - cal1.getTimeInMillis()) / 1000;
    String display = String.format("%02d:%02d:%02d", secs / 3600, (secs % 3600) / 60, (secs % 60));
    System.out.println(display);
  }
}





Format a date into dd/mm/yyyy

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Main {
  public static void main(String[] args) {
    Date date = Calendar.getInstance().getTime();
    // Display a date in day, month, year format
    DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
    String today = formatter.format(date);
    System.out.println("Today : " + today);
  }
}





Format current date and time with the SimpleDateFormat: dd/MM/yyyy

import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
  public static void main(String[] args) {
    SimpleDateFormat sdfDate = new SimpleDateFormat("dd/MM/yyyy");
    Date now = new Date();
    String strDate = sdfDate.format(now);
    System.out.println("Date: " + strDate);
  }
}
//Date: 18/02/2009





Format current date and time with the SimpleDateFormat: HH:mm:ss

import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
  public static void main(String[] args) {
    SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm:ss");
    Date now = new Date();
    String strTime = sdfTime.format(now);
    System.out.println("Time: " + strTime);
  }
}
//Time: 13:54:56





Format Date with System.out.format

/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
import java.util.Calendar;
import java.util.Locale;
public class TestFormat {
  public static void main(String[] args) {
    long n = 461012;
    System.out.format("%d%n", n);
    System.out.format("%08d%n", n);
    System.out.format("%+8d%n", n);
    System.out.format("%,8d%n", n);
    System.out.format("%+,8d%n%n", n);
    double pi = Math.PI;
    System.out.format("%f%n", pi);
    System.out.format("%.3f%n", pi);
    System.out.format("%10.3f%n", pi);
    System.out.format("%-10.3f%n", pi);
    System.out.format(Locale.FRANCE, "%-10.4f%n%n", pi);
    Calendar c = Calendar.getInstance();
    System.out.format("%tB %te, %tY%n", c, c, c);
    System.out.format("%tl:%tM %tp%n", c, c, c);
    System.out.format("%tD%n", c);
  }
}





Formatter that caches formatted date information

/*
 * 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.
 */

import java.util.Date;
import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
/**
 * Fast date formatter that caches recently formatted date information
 * and uses it to avoid too-frequent calls to the underlying
 * formatter.  Note: breaks fieldPosition param of format(Date,
 * StringBuffer, FieldPosition).  If you care about the field
 * position, call the underlying DateFormat directly.
 *
 * @author Stan Bailes
 * @author Alex Chaffee
 **/
public class FastDateFormat extends DateFormat {
    DateFormat    df;
    long          lastSec = -1;
    StringBuffer  sb      = new StringBuffer();
    FieldPosition fp      = new FieldPosition(DateFormat.MILLISECOND_FIELD);
    public FastDateFormat(DateFormat df) {
        this.df = df;
    }
    public Date parse(String text, ParsePosition pos) {
        return df.parse(text, pos);
    }
    /**
     * Note: breaks functionality of fieldPosition param. Also:
     * there"s a bug in SimpleDateFormat with "S" and "SS", use "SSS"
     * instead if you want a msec field.
     **/
    public StringBuffer format(Date date, StringBuffer toAppendTo,
                               FieldPosition fieldPosition) {
        long dt = date.getTime();
        long ds = dt / 1000;
        if (ds != lastSec) {
            sb.setLength(0);
            df.format(date, sb, fp);
            lastSec = ds;
        } else {
            // munge current msec into existing string
            int ms = (int)(dt % 1000);
            int pos = fp.getEndIndex();
            int begin = fp.getBeginIndex();
            if (pos > 0) {
                if (pos > begin)
                    sb.setCharAt(--pos, Character.forDigit(ms % 10, 10));
                ms /= 10;
                if (pos > begin)
                    sb.setCharAt(--pos, Character.forDigit(ms % 10, 10));
                ms /= 10;
                if (pos > begin)
                    sb.setCharAt(--pos, Character.forDigit(ms % 10, 10));
            }
        }
        toAppendTo.append(sb.toString());
        return toAppendTo;
    }
    public static void main(String[] args) {
        String format = "yyyy-MM-dd HH:mm:ss.SSS";
        if (args.length > 0)
            format = args[0];
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        FastDateFormat fdf = new FastDateFormat(sdf);
        Date d = new Date();
        d.setTime(1); System.out.println(fdf.format(d) + "\t" + sdf.format(d));
        d.setTime(20); System.out.println(fdf.format(d) + "\t" + sdf.format(d));
        d.setTime(500); System.out.println(fdf.format(d) + "\t" + sdf.format(d));
        d.setTime(543); System.out.println(fdf.format(d) + "\t" + sdf.format(d));
        d.setTime(999); System.out.println(fdf.format(d) + "\t" + sdf.format(d));
        d.setTime(1050); System.out.println(fdf.format(d) + "\t" + sdf.format(d));
        d.setTime(2543); System.out.println(fdf.format(d) + "\t" + sdf.format(d));
        d.setTime(12345); System.out.println(fdf.format(d) + "\t" + sdf.format(d));
        d.setTime(12340); System.out.println(fdf.format(d) + "\t" + sdf.format(d));
        final int reps = 100000;
        {
            long start = System.currentTimeMillis();
            for (int i = 0; i < reps; i++) {
                d.setTime(System.currentTimeMillis());
                fdf.format(d);
            }
            long elap = System.currentTimeMillis() - start;
            System.out.println("fast: " + elap + " elapsed");
            System.out.println(fdf.format(d));
        }
        {
            long start = System.currentTimeMillis();
            for (int i = 0; i < reps; i++) {
                d.setTime(System.currentTimeMillis());
                sdf.format(d);
            }
            long elap = System.currentTimeMillis() - start;
            System.out.println("slow: " + elap + " elapsed");
            System.out.println(sdf.format(d));
        }
    }
}





Formatting Dates and Times

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
public class MainClass {
  public static void main(String[] args) {
    Date today = new Date();
    DateFormat fmt = DateFormat.getDateTimeInstance(DateFormat.FULL,
                                                           DateFormat.FULL, Locale.US);
    String formatted = fmt.format(today);
    System.out.println(formatted);
  }
}



Tuesday, January 16, 2007 10:03:23 AM PST


Formatting String Symbols for SimpleDateFormat

Symbol           Description
a                AM or PM
d                Day of month (1-31)
h                Hour in AM/PM (1-12)
k                Hour in day (1-24)
m                Minute in hour (0-59)
s                Second in minute (0-59)
w                Week of year (1-52)
y                Year
z                Time zone
D                Day of year (1-366)
E                Day of week (for example, Thursday)
F                Day of week in month
G                Era (that is, AD or BC)
H                Hour in day (0-23)
K                Hour in AM/PM (0-11)
M                Month
S                Millisecond in second
W                Week of month (1-5)
Z                Time zone in RFC822 format





Formatting Symbols for SimpleDateFormat

Symbol                              Description
a                                   AM or PM
d                                   Day of month (1-31)
h                                   Hour in AM/PM (1-12)
k                                   Hour in day (1-24)
m                                   Minute in hour (0-59)
s                                   Second in minute (0-59)
w                                   Week of year (1-52)
y                                   Year
z                                   Time zone
D                                   Day of year (1-366)
E                                   Day of week (for example, Thursday)
F                                   Day of week in month
G                                   Era (that is, AD or BC)
H                                   Hour in day (0-23)
K                                   Hour in AM/PM (0-11)
M                                   Month
S                                   Millisecond in second
W                                   Week of month (1-5)
Z                                   Time zone in RFC822 format





Formatting the Time Using a Custom Format

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
  public static void main(String[] argv) throws Exception {
    // The hour (1-12)
    Format formatter = new SimpleDateFormat("h");
    String s = formatter.format(new Date());
    System.out.println(s);
  }
}





Four different date formats for four countries: US, UK, GERMANY, FRANCE

import static java.text.DateFormat.FULL;
import static java.text.DateFormat.LONG;
import static java.text.DateFormat.MEDIUM;
import static java.text.DateFormat.SHORT;
import static java.util.Locale.FRANCE;
import static java.util.Locale.GERMANY;
import static java.util.Locale.UK;
import static java.util.Locale.US;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
public class MainClass {
  public static void main(String[] args) {
    Date today = new Date();
    Locale[] locales = { US, UK, GERMANY, FRANCE };
    int[] styles = { FULL, LONG, MEDIUM, SHORT };
    String[] styleNames = { "FULL", "LONG", "MEDIUM", "SHORT" };
    DateFormat fmt = null;
    for (Locale locale : locales) {
      System.out.println("\nThe Date for " + locale.getDisplayCountry() + ":");
      for (int i = 0; i < styles.length; i++) {
        fmt = DateFormat.getDateInstance(styles[i], locale);
        System.out.println("\tIn " + styleNames[i] + " is " + fmt.format(today));
      }
    }
  }
}



The Date for United States:
  In FULL is Tuesday, January 16, 2007
  In LONG is January 16, 2007
  In MEDIUM is Jan 16, 2007
  In SHORT is 1/16/07
The Date for United Kingdom:
  In FULL is 16 January 2007
  In LONG is 16 January 2007
  In MEDIUM is 16-Jan-2007
  In SHORT is 16/01/07
The Date for Germany:
  In FULL is Dienstag, 16. Januar 2007
  In LONG is 16. Januar 2007
  In MEDIUM is 16.01.2007
  In SHORT is 16.01.07
The Date for France:
  In FULL is mardi 16 janvier 2007
  In LONG is 16 janvier 2007
  In MEDIUM is 16 janv. 2007
  In SHORT is 16/01/07


Get a List of Short Month Names

import java.text.DateFormatSymbols;
public class Main {
  public static void main(String[] args) {
    String[] shortMonths = new DateFormatSymbols().getShortMonths();
    for (int i = 0; i < shortMonths.length; i++) {
      String shortMonth = shortMonths[i];
      System.out.println("shortMonth = " + shortMonth);
    }
  }
}





Get a List of Short Weekday Names

import java.text.DateFormatSymbols;
public class Main {
  public static void main(String[] args) {
    String[] shortWeekdays = new DateFormatSymbols().getShortWeekdays();
    for (int i = 0; i < shortWeekdays.length; i++) {
      String shortWeekday = shortWeekdays[i];
      System.out.println("shortWeekday = " + shortWeekday);
    }
  }
}





Get a List of Weekday Names

import java.text.DateFormatSymbols;
public class Main {
  public static void main(String[] args) {
    String[] weekdays = new DateFormatSymbols().getWeekdays();
    for (int i = 0; i < weekdays.length; i++) {
      String weekday = weekdays[i];
      System.out.println("weekday = " + weekday);
    }
  }
}





Leniency

Leniency refers to whether or not a strict rule will be applied at parsing. If a DateFormat object is lenient, it will accept Jan 32, 2005. In fact, it will take the liberty of converting it to Feb 1, 2006. By default, a DateFormat object is lenient.



import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
public class MainClass {
  public static void main(String[] args) {
    DateFormat shortDf = DateFormat.getDateInstance(DateFormat.SHORT);
    DateFormat mediumDf = DateFormat.getDateInstance(DateFormat.MEDIUM);
    DateFormat longDf = DateFormat.getDateInstance(DateFormat.LONG);
    DateFormat fullDf = DateFormat.getDateInstance(DateFormat.FULL);
    System.out.println(shortDf.format(new Date()));
    System.out.println(mediumDf.format(new Date()));
    System.out.println(longDf.format(new Date()));
    System.out.println(fullDf.format(new Date()));
    // parsing
    try {
      Date date = shortDf.parse("Jan 32, 2005");
    } catch (ParseException e) {
    }
  }
}



1/26/07
Jan 26, 2007
January 26, 2007
Friday, January 26, 2007


Output current time: %tc

import java.util.Calendar;
public class Main {
  public static void main(String[] argv) throws Exception {
    Calendar cal = Calendar.getInstance();
    System.out.printf("Current time and date: %tc\n", cal);
  }
}





Parse a date and time

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
  public static void main(String[] argv) throws Exception {
    Format formatter = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
    Date date = (Date) formatter.parseObject("2002.01.29.08.36.33");
    System.out.println(date);
  }
}





Parse string date value input with SimpleDateFormat("dd-MMM-yy")

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
  public static void main(String[] argv) throws Exception {
    Format formatter = new SimpleDateFormat("dd-MMM-yy");
    Date date = (Date) formatter.parseObject("29-Jan-02");
    System.out.println(date);
  }
}





Parse string date value input with SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z")

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
  public static void main(String[] argv) throws Exception {
    Format formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
    Date date = (Date) formatter.parseObject("Tue, 29 Jan 2004 21:14:02 -0500");
  }
}





Parse string date value with default format: DateFormat.getDateInstance(DateFormat.DEFAULT)

import java.text.DateFormat;
import java.util.Date;
public class Main {
  public static void main(String[] argv) throws Exception {
    Date date = DateFormat.getDateInstance(DateFormat.DEFAULT).parse("Feb 28, 2002");
    System.out.println(date);
  }
}





Parse with a custom format

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Main {
  public static void main(String[] argv) throws Exception {
    Format formatter = new SimpleDateFormat("HH:mm:ss Z", Locale.CANADA);
    Date date = (Date) formatter.parseObject("21:44:07 Heure normale du Pacifique");
  }
}





Parse with a default format

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
public class Main {
  public static void main(String[] argv) throws Exception {
    Date date = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.CANADA).parse("21:44:07");
  }
}





Parsing the Time Using a Custom Format

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
  public static void main(String[] argv) throws Exception {
    DateFormat formatter = new SimpleDateFormat("hh.mm.ss a");
    Date date = (Date) formatter.parse("02.47.44 PM");
    System.out.println(date);
  }
}





print out the current date and time

import java.text.DateFormat;
import java.util.Calendar;
public class CalendarManipulation {
  public static void main(String s[]) {
    Calendar cal = Calendar.getInstance();
    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL,
        DateFormat.MEDIUM);
    System.out.println(df.format(cal.getTime()));
  }
}





RFC date format

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.TimeZone;
/**
 *  Common place for date utils.
 *
 * @author dac@eng.sun.ru
 * @author Jason Hunter [jch@eng.sun.ru]
 * @author James Todd [gonzo@eng.sun.ru]
 * @author Costin Manolache
 */
public class DateTool {

    /**
     * US locale - all HTTP dates are in english
     */
    public final static Locale LOCALE_US = Locale.US;
    /**
     * GMT timezone - all HTTP dates are on GMT
     */
    public final static TimeZone GMT_ZONE = TimeZone.getTimeZone("GMT");
    /**
     * format for RFC 1123 date string -- "Sun, 06 Nov 1994 08:49:37 GMT"
     */
    public final static String RFC1123_PATTERN =
        "EEE, dd MMM yyyyy HH:mm:ss z";
    /** 
     * Format for http response header date field
     */
    public static final String HTTP_RESPONSE_DATE_HEADER =
        "EEE, dd MMM yyyy HH:mm:ss zzz";
    // format for RFC 1036 date string -- "Sunday, 06-Nov-94 08:49:37 GMT"
    private final static String rfc1036Pattern =
        "EEEEEEEEE, dd-MMM-yy HH:mm:ss z";
    // format for C asctime() date string -- "Sun Nov  6 08:49:37 1994"
    private final static String asctimePattern =
        "EEE MMM d HH:mm:ss yyyyy";
    /**
     * Pattern used for old cookies
     */
    public final static String OLD_COOKIE_PATTERN = "EEE, dd-MMM-yyyy HH:mm:ss z";
    /**
     * DateFormat to be used to format dates
     */
    public final static DateFormat rfc1123Format =
        new SimpleDateFormat(RFC1123_PATTERN, LOCALE_US);
    /**
     * DateFormat to be used to format old netscape cookies
     */
    public final static DateFormat oldCookieFormat =
        new SimpleDateFormat(OLD_COOKIE_PATTERN, LOCALE_US);
    public final static DateFormat rfc1036Format =
        new SimpleDateFormat(rfc1036Pattern, LOCALE_US);
    public final static DateFormat asctimeFormat =
        new SimpleDateFormat(asctimePattern, LOCALE_US);
    static {
        rfc1123Format.setTimeZone(GMT_ZONE);
        oldCookieFormat.setTimeZone(GMT_ZONE);
        rfc1036Format.setTimeZone(GMT_ZONE);
        asctimeFormat.setTimeZone(GMT_ZONE);
    }
}





SimpleDateFormat

With SimpleDateFormat, you can set your own date patterns. For example, dd/mm/yyyy, mm/dd/yyyy, yyyy-mm-dd, and so on.

The following pattern letters are defined (all other characters from "A" to "Z" and from "a" to "z" are reserved):



Letter   Date or Time Component   Presentation       Examples
G        Era designator             Text                AD
y        Year                       Year                1996;    96
M        Month in year               Month               July; Jul; 07
w        Week in year               Number               27
W        Week in month               Number               2
D        Day in year               Number               189
d        Day in month               Number               10
F        Day of week in month       Number               2
E        Day in week               Text               Tuesday; Tue
a        Am/pm marker               Text               PM
H        Hour in day (0-23)       Number               0
k        Hour in day (1-24)       Number               24
K        Hour in am/pm (0-11)       Number               0
h        Hour in am/pm (1-12)       Number               12
m        Minute in hour           Number               30
s        Second in minute           Number               55
S        Millisecond                Number               978
z        Time zone                   General time zone   Pacific Standard Time; PST; GMT-08:00
Z        Time zone                  RFC 822 time zone   -0800
(from Java API doc)





SimpleDateFormat: hh:mm:ss, dd MMM yyyy hh:mm:ss zzz, E MMM dd yyyy

import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatDemo {
  public static void main(String args[]) {
    Date date = new Date();
    SimpleDateFormat sdf;
    sdf = new SimpleDateFormat("hh:mm:ss");
    System.out.println(sdf.format(date));
    sdf = new SimpleDateFormat("dd MMM yyyy hh:mm:ss zzz");
    System.out.println(sdf.format(date));
    sdf = new SimpleDateFormat("E MMM dd yyyy");
    System.out.println(sdf.format(date));
  }
}





Simply format a date as YYYYMMDD

import java.util.GregorianCalendar;
public class Main {
  public static void main(String[] argv) throws Exception {
    GregorianCalendar gc = new GregorianCalendar();
    gc.setLenient(false);
    gc.set(GregorianCalendar.YEAR, 2003);
    gc.set(GregorianCalendar.MONTH, 12);
    gc.set(GregorianCalendar.DATE, 1);
    int m = gc.get(GregorianCalendar.MONTH) + 1;
    int d = gc.get(GregorianCalendar.DATE);
    String mm = Integer.toString(m);
    String dd = Integer.toString(d);
    System.out.println(gc.get(GregorianCalendar.YEAR) + (m < 10 ? "0" + mm : mm)
        + (d < 10 ? "0" + dd : dd));
  }
}





Time in 12-hour format

import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
  public static void main(String[] argv) throws Exception {
    Date date = new Date();
    SimpleDateFormat simpDate;
    simpDate = new SimpleDateFormat("hh:mm:ss a");
    System.out.println(simpDate.format(date));
  }
}





Time in 24-hour format

import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
  public static void main(String[] argv) throws Exception {
    Date date = new Date();
    SimpleDateFormat simpDate;
    simpDate = new SimpleDateFormat("kk:mm:ss");
    System.out.println(simpDate.format(date));
  }
}





Various Date format

/*
 *
 * Copyright (c) 1998 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
 * modify and redistribute this software in source and binary code form,
 * provided that i) this copyright notice and license appear on all copies of
 * the software; and ii) Licensee does not utilize the software in a manner
 * which is disparaging to Sun.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
 * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
 * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
 * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
 * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
 * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
 * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
 * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
 * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES.
 *
 * This software is not designed or intended for use in on-line control of
 * aircraft, air traffic, aircraft navigation or aircraft communications; or in
 * the design, construction, operation or maintenance of any nuclear
 * facility. Licensee represents and warrants that it will not use or
 * redistribute the Software for such purposes.
 */

import java.awt.Color;
import java.awt.ruponent;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class ComboBoxDemo2 extends JPanel implements ActionListener {
  static JFrame frame;
  JLabel result;
  String currentPattern;
  public ComboBoxDemo2() {
    setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
    String[] patternExamples = { "dd MMMMM yyyy", "dd.MM.yy", "MM/dd/yy",
        "yyyy.MM.dd G "at" hh:mm:ss z", "EEE, MMM d, ""yy", "h:mm a", "H:mm:ss:SSS", "K:mm a,z",
        "yyyy.MMMMM.dd GGG hh:mm aaa" };
    currentPattern = patternExamples[0];
    // Set up the UI for selecting a pattern.
    JLabel patternLabel1 = new JLabel("Enter the pattern string or");
    JLabel patternLabel2 = new JLabel("select one from the list:");
    JComboBox patternList = new JComboBox(patternExamples);
    patternList.setEditable(true);
    patternList.addActionListener(this);
    // Create the UI for displaying result.
    JLabel resultLabel = new JLabel("Current Date/Time", JLabel.LEADING); // ==
                                                                          // LEFT
    result = new JLabel(" ");
    result.setForeground(Color.black);
    result.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createLineBorder(Color.black), BorderFactory.createEmptyBorder(5, 5, 5, 5)));
    // Lay out everything.
    JPanel patternPanel = new JPanel();
    patternPanel.setLayout(new BoxLayout(patternPanel, BoxLayout.PAGE_AXIS));
    patternPanel.add(patternLabel1);
    patternPanel.add(patternLabel2);
    patternList.setAlignmentX(Component.LEFT_ALIGNMENT);
    patternPanel.add(patternList);
    JPanel resultPanel = new JPanel(new GridLayout(0, 1));
    resultPanel.add(resultLabel);
    resultPanel.add(result);
    patternPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
    resultPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
    add(patternPanel);
    add(Box.createRigidArea(new Dimension(0, 10)));
    add(resultPanel);
    setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    reformat();
  } // constructor
  public void actionPerformed(ActionEvent e) {
    JComboBox cb = (JComboBox) e.getSource();
    String newSelection = (String) cb.getSelectedItem();
    currentPattern = newSelection;
    reformat();
  }
  /** Formats and displays today"s date. */
  public void reformat() {
    Date today = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat(currentPattern);
    try {
      String dateString = formatter.format(today);
      result.setForeground(Color.black);
      result.setText(dateString);
    } catch (IllegalArgumentException iae) {
      result.setForeground(Color.red);
      result.setText("Error: " + iae.getMessage());
    }
  }
  /**
   * Create the GUI and show it. For thread safety, this method should be
   * invoked from the event-dispatching thread.
   */
  private static void createAndShowGUI() {
    // Create and set up the window.
    JFrame frame = new JFrame("ComboBoxDemo2");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Create and set up the content pane.
    JComponent newContentPane = new ComboBoxDemo2();
    newContentPane.setOpaque(true); // content panes must be opaque
    frame.setContentPane(newContentPane);
    // Display the window.
    frame.pack();
    frame.setVisible(true);
  }
  public static void main(String[] args) {
    // Schedule a job for the event-dispatching thread:
    // creating and showing this application"s GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGUI();
      }
    });
  }
}