Java/Development Class/Calendar Date

Материал из Java эксперт
Перейти к: навигация, поиск

Содержание

Add 10 months to the calendar

   <source lang="java">
    

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   Calendar cal = Calendar.getInstance();
   System.out.println("Today : " + cal.getTime());
   // Subtract 30 days from the calendar
   cal.add(Calendar.DATE, -30);
   System.out.println("30 days ago: " + cal.getTime());
 }

}



 </source>
   
  
 
  



Add hours, minutes or seconds to a date

   <source lang="java">
    

import java.util.Calendar;

public class DateAddHour {

   public static void main(String[] args) {
       Calendar calendar = Calendar.getInstance();
       System.out.println("Original = " + calendar.getTime());

       // Subtract 2 hour from the current time
       calendar.add(Calendar.HOUR, -2);

       // Add 30 minutes to the calendar time
       calendar.add(Calendar.MINUTE, 30);

       // Add 300 seconds to the calendar time
       calendar.add(Calendar.SECOND, 300);
       System.out.println("Updated  = " + calendar.getTime());
   }

}




 </source>
   
  
 
  



Add hours to current date using Calendar.add method

   <source lang="java">
    

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   Calendar now = Calendar.getInstance();
   System.out.println("Current Date : " + (now.get(Calendar.MONTH) + 1) + "-"
       + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
   System.out.println("Current time : " + now.get(Calendar.HOUR_OF_DAY) + ":"
       + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));
    now.add(Calendar.HOUR, 10);
   System.out.println("New time after adding 10 hours : " + now.get(Calendar.HOUR_OF_DAY) + ":"
       + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));
 }

}



 </source>
   
  
 
  



Add minutes to current date using Calendar.add method

   <source lang="java">
    

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   Calendar now = Calendar.getInstance();
   System.out.println("Current time : " + now.get(Calendar.HOUR_OF_DAY) + ":"
       + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));
   now.add(Calendar.MINUTE, 20);
   System.out.println("New time after adding 20 minutes : " + now.get(Calendar.HOUR_OF_DAY) + ":"
       + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));
 }

}



 </source>
   
  
 
  



Add months to current date using Calendar.add method

   <source lang="java">
    

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   Calendar now = Calendar.getInstance();
   System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1) + "-"
       + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
   
   now.add(Calendar.MONTH, 10);
   System.out.println("date after 10 months : " + (now.get(Calendar.MONTH) + 1) + "-"
       + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
 }

}



 </source>
   
  
 
  



Add or subtract days to current date using Java Calendar

   <source lang="java">
    
      

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   Calendar now = Calendar.getInstance();
   System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1) + "-"
       + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
   // add days to current date using Calendar.add method
   now.add(Calendar.DATE, 1);
   System.out.println("date after one day : " + (now.get(Calendar.MONTH) + 1) + "-"
       + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
 }

} /* Current date : 2-20-2009 date after one day : 2-21-2009

  • /



 </source>
   
  
 
  



Add seconds to current date using Calendar.add method

   <source lang="java">
    

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   Calendar now = Calendar.getInstance();
   System.out.println("Current time : " + now.get(Calendar.HOUR_OF_DAY) + ":"
       + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));
   now.add(Calendar.SECOND, 100);
   System.out.println("New time after adding 100 seconds : " + now.get(Calendar.HOUR_OF_DAY) + ":"
       + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));
 }

}



 </source>
   
  
 
  



Add week to current date using Calendar.add method

   <source lang="java">
    

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   Calendar now = Calendar.getInstance();
   System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1) + "-"
       + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
   System.out.println("Current week of month is : " + now.get(Calendar.WEEK_OF_MONTH));
   System.out.println("Current week of year is : " + now.get(Calendar.WEEK_OF_YEAR));
   
   now.add(Calendar.WEEK_OF_YEAR, 1);
   System.out.println("date after one week : " + (now.get(Calendar.MONTH) + 1) + "-"
       + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
 }

}



 </source>
   
  
 
  



Add year to current date using Calendar.add method

   <source lang="java">
    

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   Calendar now = Calendar.getInstance();
   System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1) + "-"
       + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
   
   now.add(Calendar.YEAR, 1);
   System.out.println("date after one year : " + (now.get(Calendar.MONTH) + 1) + "-"
       + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
 }

}



 </source>
   
  
 
  



Bean to display a month calendar in a JPanel

   <source lang="java">
    

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

import java.awt.BorderLayout; import java.awt.Color; import java.awt.ruponent; import java.awt.Container; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Calendar; import java.util.GregorianCalendar; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JPanel; /**

* Bean to display a month calendar in a JPanel. Only works for the Western
* calendar.
* 
* @author Ian F. Darwin, http://www.darwinsys.ru/
* @version $Id: Cal.java,v 1.5 2004/02/09 03:33:45 ian Exp $
*/

public class Cal extends JPanel {

 /** The currently-interesting year (not modulo 1900!) */
 protected int yy;
 /** Currently-interesting month and day */
 protected int mm, dd;
 /** The buttons to be displayed */
 protected JButton labs[][];
 /** The number of day squares to leave blank at the start of this month */
 protected int leadGap = 0;
 /** A Calendar object used throughout */
 Calendar calendar = new GregorianCalendar();
 /** Today"s year */
 protected final int thisYear = calendar.get(Calendar.YEAR);
 /** Today"s month */
 protected final int thisMonth = calendar.get(Calendar.MONTH);
 /** One of the buttons. We just keep its reference for getBackground(). */
 private JButton b0;
 /** The month choice */
 private JComboBox monthChoice;
 /** The year choice */
 private JComboBox yearChoice;
 /**
  * Construct a Cal, starting with today.
  */
 Cal() {
   super();
   setYYMMDD(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
       calendar.get(Calendar.DAY_OF_MONTH));
   buildGUI();
   recompute();
 }
 /**
  * Construct a Cal, given the leading days and the total days
  * 
  * @exception IllegalArgumentException
  *                If year out of range
  */
 Cal(int year, int month, int today) {
   super();
   setYYMMDD(year, month, today);
   buildGUI();
   recompute();
 }
 private void setYYMMDD(int year, int month, int today) {
   yy = year;
   mm = month;
   dd = today;
 }
 String[] months = { "January", "February", "March", "April", "May", "June",
     "July", "August", "September", "October", "November", "December" };
 /** Build the GUI. Assumes that setYYMMDD has been called. */
 private void buildGUI() {
   getAccessibleContext().setAccessibleDescription(
       "Calendar not accessible yet. Sorry!");
   setBorder(BorderFactory.createEtchedBorder());
   setLayout(new BorderLayout());
   JPanel tp = new JPanel();
   tp.add(monthChoice = new JComboBox());
   for (int i = 0; i < months.length; i++)
     monthChoice.addItem(months[i]);
   monthChoice.setSelectedItem(months[mm]);
   monthChoice.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent ae) {
       int i = monthChoice.getSelectedIndex();
       if (i >= 0) {
         mm = i;
         // System.out.println("Month=" + mm);
         recompute();
       }
     }
   });
   monthChoice.getAccessibleContext().setAccessibleName("Months");
   monthChoice.getAccessibleContext().setAccessibleDescription(
       "Choose a month of the year");
   tp.add(yearChoice = new JComboBox());
   yearChoice.setEditable(true);
   for (int i = yy - 5; i < yy + 5; i++)
     yearChoice.addItem(Integer.toString(i));
   yearChoice.setSelectedItem(Integer.toString(yy));
   yearChoice.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent ae) {
       int i = yearChoice.getSelectedIndex();
       if (i >= 0) {
         yy = Integer.parseInt(yearChoice.getSelectedItem()
             .toString());
         // System.out.println("Year=" + yy);
         recompute();
       }
     }
   });
   add(BorderLayout.CENTER, tp);
   JPanel bp = new JPanel();
   bp.setLayout(new GridLayout(7, 7));
   labs = new JButton[6][7]; // first row is days
   bp.add(b0 = new JButton("S"));
   bp.add(new JButton("M"));
   bp.add(new JButton("T"));
   bp.add(new JButton("W"));
   bp.add(new JButton("R"));
   bp.add(new JButton("F"));
   bp.add(new JButton("S"));
   ActionListener dateSetter = new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       String num = e.getActionCommand();
       if (!num.equals("")) {
         // set the current day highlighted
         setDayActive(Integer.parseInt(num));
         // When this becomes a Bean, you can
         // fire some kind of DateChanged event here.
         // Also, build a similar daySetter for day-of-week btns.
       }
     }
   };
   // Construct all the buttons, and add them.
   for (int i = 0; i < 6; i++)
     for (int j = 0; j < 7; j++) {
       bp.add(labs[i][j] = new JButton(""));
       labs[i][j].addActionListener(dateSetter);
     }
   add(BorderLayout.SOUTH, bp);
 }
 public final static int dom[] = { 31, 28, 31, 30, /* jan feb mar apr */
 31, 30, 31, 31, /* may jun jul aug */
 30, 31, 30, 31 /* sep oct nov dec */
 };
 /** Compute which days to put where, in the Cal panel */
 protected void recompute() {
   // System.out.println("Cal::recompute: " + yy + ":" + mm + ":" + dd);
   if (mm < 0 || mm > 11)
     throw new IllegalArgumentException("Month " + mm
         + " bad, must be 0-11");
   clearDayActive();
   calendar = new GregorianCalendar(yy, mm, dd);
   // Compute how much to leave before the first.
   // getDay() returns 0 for Sunday, which is just right.
   leadGap = new GregorianCalendar(yy, mm, 1).get(Calendar.DAY_OF_WEEK) - 1;
   // System.out.println("leadGap = " + leadGap);
   int daysInMonth = dom[mm];
   if (isLeap(calendar.get(Calendar.YEAR)) && mm > 1)
     ++daysInMonth;
   // Blank out the labels before 1st day of month
   for (int i = 0; i < leadGap; i++) {
     labs[0][i].setText("");
   }
   // Fill in numbers for the day of month.
   for (int i = 1; i <= daysInMonth; i++) {
     JButton b = labs[(leadGap + i - 1) / 7][(leadGap + i - 1) % 7];
     b.setText(Integer.toString(i));
   }
   // 7 days/week * up to 6 rows
   for (int i = leadGap + 1 + daysInMonth; i < 6 * 7; i++) {
     labs[(i) / 7][(i) % 7].setText("");
   }
   // Shade current day, only if current month
   if (thisYear == yy && mm == thisMonth)
     setDayActive(dd); // shade the box for today
   // Say we need to be drawn on the screen
   repaint();
 }
 /**
  * isLeap() returns true if the given year is a Leap Year.
  * 
  * "a year is a leap year if it is divisible by 4 but not by 100, except
  * that years divisible by 400 *are* leap years." -- Kernighan & Ritchie,
  * _The C Programming Language_, p 37.
  */
 public boolean isLeap(int year) {
   if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
     return true;
   return false;
 }
 /** Set the year, month, and day */
 public void setDate(int yy, int mm, int dd) {
   // System.out.println("Cal::setDate");
   this.yy = yy;
   this.mm = mm; // starts at 0, like Date
   this.dd = dd;
   recompute();
 }
 /** Unset any previously highlighted day */
 private void clearDayActive() {
   JButton b;
   // First un-shade the previously-selected square, if any
   if (activeDay > 0) {
     b = labs[(leadGap + activeDay - 1) / 7][(leadGap + activeDay - 1) % 7];
     b.setBackground(b0.getBackground());
     b.repaint();
     activeDay = -1;
   }
 }
 private int activeDay = -1;
 /** Set just the day, on the current month */
 public void setDayActive(int newDay) {
   clearDayActive();
   // Set the new one
   if (newDay <= 0)
     dd = new GregorianCalendar().get(Calendar.DAY_OF_MONTH);
   else
     dd = newDay;
   // Now shade the correct square
   Component square = labs[(leadGap + newDay - 1) / 7][(leadGap + newDay - 1) % 7];
   square.setBackground(Color.red);
   square.repaint();
   activeDay = newDay;
 }
 /** For testing, a main program */
 public static void main(String[] av) {
   JFrame f = new JFrame("Cal");
   Container c = f.getContentPane();
   c.setLayout(new FlowLayout());
   // for this test driver, hardcode 1995/02/10.
   c.add(new Cal(1995, 2 - 1, 10));
   // and beside it, the current month.
   c.add(new Cal());
   f.pack();
   f.setVisible(true);
 }

}




 </source>
   
  
 
  



Calculate the age

   <source lang="java">
    

import java.util.Calendar; import java.util.GregorianCalendar; public class Main {

 public static void main(String[] args) {
   Calendar cal = new GregorianCalendar(1999, 1, 1);
   Calendar now = new GregorianCalendar();
   int res = now.get(Calendar.YEAR) - cal.get(Calendar.YEAR);
   if ((cal.get(Calendar.MONTH) > now.get(Calendar.MONTH))
       || (cal.get(Calendar.MONTH) == now.get(Calendar.MONTH) && cal.get(Calendar.DAY_OF_MONTH) > now
           .get(Calendar.DAY_OF_MONTH))) {
     res--;
   }
   System.out.println(res);
 }

}



 </source>
   
  
 
  



Calendar adjust date automatically

   <source lang="java">
    

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   Calendar now = Calendar.getInstance();
   System.out.println("Current Date : " + (now.get(Calendar.MONTH) + 1) + "-"
       + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
   System.out.println("Current time : " + now.get(Calendar.HOUR_OF_DAY) + ":"
       + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));
  System.out.println("New date after adding 10 hours : " + (now.get(Calendar.MONTH) + 1) + "-"
      + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));  }

}



 </source>
   
  
 
  



Calendar Comparator

   <source lang="java">
  

/*

* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors.  All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program 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 distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA  02110-1301  USA
*
*/

import java.util.Calendar; import java.util.ruparator; /**

* @author Gavin King
*/

public class CalendarComparator implements Comparator {

 public int compare(Object x, Object y) {
   Calendar xcal = (Calendar) x;
   Calendar ycal = (Calendar) y;
   if ( xcal.before(ycal) ) return -1;
   if ( xcal.after(ycal) ) return 1;
   return 0;
 }
 
 public static final Comparator INSTANCE = new CalendarComparator();

}


 </source>
   
  
 
  



Calendar Demo

   <source lang="java">
    

import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class CalendarDemo {

 /** The Date we are about to format */
 Date timeNow;
 /**
  * A calendar formatting object, used throughout. Note that other forms of
  * the Calendar constructor let you pass in Locale, TimeZone, or both, or
  * yy,mm,dd,[hh, mm [, ss]] You can also set your own Daylight Saving rules,
  * fiddle the Gregorian cutover of 1582, and probably the phase of the moon!
  */
 Calendar calendar = new GregorianCalendar();
 public static void main(String[] a) {
   new CalendarDemo().format();
 }
 /** Construct a CalendarDemo object with the current date/time */
 CalendarDemo() {
   timeNow = new Date();
 }
 public void format() {
   // Tell the calendar what date/time to format
   calendar.setTime(timeNow);
   // print out most of the known fields
   System.out.println("ERA: " + calendar.get(Calendar.ERA));
   System.out.println("YEAR: " + calendar.get(Calendar.YEAR));
   System.out.println("MONTH: " + calendar.get(Calendar.MONTH));
   System.out.println("WEEK_OF_YEAR: "
       + calendar.get(Calendar.WEEK_OF_YEAR));
   System.out.println("WEEK_OF_MONTH: "
       + calendar.get(Calendar.WEEK_OF_MONTH));
   System.out.println("DATE: " + calendar.get(Calendar.DATE));
   System.out.println("DAY_OF_MONTH: "
       + calendar.get(Calendar.DAY_OF_MONTH));
   System.out
       .println("DAY_OF_YEAR: " + calendar.get(Calendar.DAY_OF_YEAR));
   System.out
       .println("DAY_OF_WEEK: " + calendar.get(Calendar.DAY_OF_WEEK));
   System.out.println("DAY_OF_WEEK_IN_MONTH: "
       + calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH));
   System.out.println("AM_PM: " + calendar.get(Calendar.AM_PM));
   System.out.println("HOUR: " + calendar.get(Calendar.HOUR));
   System.out
       .println("HOUR_OF_DAY: " + calendar.get(Calendar.HOUR_OF_DAY));
   System.out.println("MINUTE: " + calendar.get(Calendar.MINUTE));
   System.out.println("SECOND: " + calendar.get(Calendar.SECOND));
   System.out
       .println("MILLISECOND: " + calendar.get(Calendar.MILLISECOND));
   System.out.println("ZONE_OFFSET: "
       + (calendar.get(Calendar.ZONE_OFFSET) / (60 * 60 * 1000)));
   System.out.println("DST_OFFSET: "
       + (calendar.get(Calendar.DST_OFFSET) / (60 * 60 * 1000)));
 }

}





 </source>
   
  
 
  



Calendar To String

   <source lang="java">
  

/*******************************************************************************

* Copyright 2008 Mjrz.net
* 
* Licensed 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.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; /**

* @author Mjrz contact@mjrz.net
*
*/

public class DateUtils {

 public static final String FORMAT_YYYYMMDD = "yyyy-MM-dd";
 public static final String FORMAT_YYYYMMDD_SLASHES = "yyyy/MM/dd";
 public static final String GENERIC_DISPLAY_FORMAT = "E, dd MMM yyyy";
 public static final String TIME_DISPLAY_FORMAT = "HH mm ss";
 public static final int LAST_WEEK = 1;
 public static final int LAST_MONTH = 2;
 public static final String formatDate(Date dt, String format) {
   GregorianCalendar cal = new GregorianCalendar();
   cal.setTime(dt);
   
   java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(format);
   sdf.setTimeZone(TimeZone.getDefault());     
   return (sdf.format(cal.getTime()));   
 }
 
 public static final String getCurrentDate(String format) {
   Calendar cal = Calendar.getInstance(TimeZone.getDefault());
     java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(format);
     sdf.setTimeZone(TimeZone.getDefault());     
     return (sdf.format(cal.getTime()));
 }
 
 public static final String dateToString(Date dt, String dateformat) {
   GregorianCalendar cal = new GregorianCalendar();
   cal.setTime(dt);
   
   StringBuffer ret = new StringBuffer();
   String separator = new String();
   if(dateformat.equals(DateUtils.FORMAT_YYYYMMDD) ) {
     separator = "-";
   }
   if(dateformat.equals(DateUtils.FORMAT_YYYYMMDD_SLASHES) ) {
     separator = "/";
   }
   ret.append(cal.get(Calendar.YEAR));
   ret.append(separator);
   ret.append(cal.get(Calendar.MONTH) + 1);
   ret.append(separator);
   ret.append(cal.get(Calendar.DATE));
   return ret.toString();
 }
 
 public static final String dateToString(Date dt, String tzString, String dateformat) {
   GregorianCalendar cal = new GregorianCalendar();
   cal.setTime(dt);
   cal.setTimeZone(TimeZone.getTimeZone(tzString));
   
   StringBuffer ret = new StringBuffer();
   String separator = new String();
   if(dateformat.equals(DateUtils.FORMAT_YYYYMMDD) ) {
     separator = "-";
   }
   if(dateformat.equals(DateUtils.FORMAT_YYYYMMDD_SLASHES) ) {
     separator = "/";
   }
   ret.append(cal.get(Calendar.YEAR));
   ret.append(separator);
   ret.append(cal.get(Calendar.MONTH) + 1);
   ret.append(separator);
   ret.append(cal.get(Calendar.DATE));
   return ret.toString();
 }
 public static final String getTimeFromDate(Date dt) {
   Calendar cal = new GregorianCalendar();
   cal.setTime(dt);
   
   StringBuffer ret = new StringBuffer();
   ret.append(cal.get(Calendar.HOUR));
   ret.append(":");
   ret.append(cal.get(Calendar.MINUTE));
   
   return ret.toString();
 }
 
 public static final String getTimeFromDate(Date dt, String tzString) {
   try {
     GregorianCalendar gc = new GregorianCalendar();
     gc.setTime(dt);
     gc.setTimeZone(TimeZone.getTimeZone(tzString));
     StringBuffer ret = new StringBuffer();
     ret.append(gc.get(Calendar.HOUR));
     ret.append(":");
     ret.append(gc.get(Calendar.MINUTE));
     ret.append(" ");
     if(gc.get(Calendar.AM_PM) == 0) {
       ret.append("AM");
     }
     else { 
       ret.append("PM");
     }
     return ret.toString();
   }
   catch(Exception e) {
     return "";
   }
 }
 
 public static final String getDateTimeFromDate(Date dt, String tzString) {
   try {
     GregorianCalendar gc = new GregorianCalendar();
     gc.setTime(dt);
     gc.setTimeZone(TimeZone.getTimeZone(tzString));
     StringBuffer ret = new StringBuffer();
     ret.append(gc.get(Calendar.YEAR));
     ret.append("-");
     ret.append(gc.get(Calendar.MONTH) - 1);
     ret.append("-");
     ret.append(gc.get(Calendar.DATE));
     ret.append(" ");
     ret.append(gc.get(Calendar.HOUR));
     ret.append(":");
     ret.append(gc.get(Calendar.MINUTE));
     ret.append(" ");
     if(gc.get(Calendar.AM_PM) == 0) {
       ret.append("AM");
     }
     else { 
       ret.append("PM");
     }
     return ret.toString();
   }
   catch(Exception e) {
     return "";
   }
 }
 
 public static final String calendarToString(Calendar cal, String dateformat) {
   StringBuffer ret = new StringBuffer();
   if(dateformat.equals(FORMAT_YYYYMMDD) ) {
     ret.append(cal.get(Calendar.YEAR));
     ret.append("-");
     
     String month = null;
     int mo = cal.get(Calendar.MONTH) + 1; /* Calendar month is zero indexed, string months are not */
     if(mo < 10) {
       month = "0" + mo;
     }
     else {
       month = "" + mo;
     }
     ret.append(month);      
     
     ret.append("-");
     
     String date = null;
     int dt = cal.get(Calendar.DATE);
     if(dt < 10) {
       date = "0" + dt;
     }
     else {
       date = "" + dt;
     }
     ret.append(date);
   }
   
   return ret.toString();
 }


 public static final GregorianCalendar getCurrentCalendar(String utimezonestring) {
   try {
     GregorianCalendar gc = new GregorianCalendar();
     gc.setTimeZone(TimeZone.getTimeZone(utimezonestring));
     return gc;
   }
   catch(Exception e) {
     //If exception, return server TimeStamp
     return new GregorianCalendar();
   }
 }
 
 public static String[] getDateRange(int cmd) {
   GregorianCalendar gc = new GregorianCalendar();
   GregorianCalendar gc2 = new GregorianCalendar();
   
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); //$NON-NLS-1$
   String ret[] = new String[2];
   ret[1] = sdf.format(gc.getTime());
   
   if(cmd == LAST_WEEK) {      
     for(int i = 0; i < 7; i++) {
       gc2.add(Calendar.DATE, -1);
     }
     
   }
   if(cmd == LAST_MONTH) {
     gc2.add(Calendar.MONTH, -1);      
   }
   ret[0] = sdf.format(gc2.getTime());
   return ret;
 }
 public static final String getDayString(int day) {
   switch (day) {
     case Calendar.SUNDAY:
       return "SUNDAY";      
     case Calendar.MONDAY:
       return "MONDAY";
     case Calendar.TUESDAY:
       return "TUESDAY";
     case Calendar.WEDNESDAY:
       return "WEDNESDAY";
     case Calendar.THURSDAY:
       return "THURSDAY";
     case Calendar.FRIDAY:
       return "FRIDAY";
     case Calendar.SATURDAY:
       return "SATURDAY";
   }
   return "";
 }

}


 </source>
   
  
 
  



Checks if two calendar objects represent the same local time.

   <source lang="java">
  

import java.math.BigDecimal; import java.math.BigInteger; import java.util.Calendar; import java.util.Date; /**

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


/**

*

A suite of utilities surrounding the use of the * {@link java.util.Calendar} and {@link java.util.Date} object.

* 
*

DateUtils contains a lot of common methods considering manipulations * of Dates or Calendars. Some methods require some extra explanation. * The truncate and round methods could be considered the Math.floor(), * Math.ceil() or Math.round versions for dates * This way date-fields will be ignored in bottom-up order. * As a complement to these methods we"ve introduced some fragment-methods. * With these methods the Date-fields will be ignored in top-down order. * Since a date without a year is not a valid date, you have to decide in what * kind of date-field you want your result, for instance milliseconds or days. *

*   
*   
*
* @author 
* @author Phil Steitz
* @author Robert Scholte
* @since 2.0
* @version $Id: DateUtils.java 634096 2008-03-06 00:58:11Z niallp $
*/

public class Main {

 //-----------------------------------------------------------------------
 /**
*

Checks if two calendar objects represent the same local time.

  *
*

This method compares the values of the fields of the two objects. * In addition, both calendars must be the same of the same type.

  * 
  * @param cal1  the first calendar, not altered, not null
  * @param cal2  the second calendar, not altered, not null
  * @return true if they represent the same millisecond instant
  * @throws IllegalArgumentException if either date is null
  * @since 2.1
  */
 public static boolean isSameLocalTime(Calendar cal1, Calendar cal2) {
     if (cal1 == null || cal2 == null) {
         throw new IllegalArgumentException("The date must not be null");
     }
     return (cal1.get(Calendar.MILLISECOND) == cal2.get(Calendar.MILLISECOND) &&
             cal1.get(Calendar.SECOND) == cal2.get(Calendar.SECOND) &&
             cal1.get(Calendar.MINUTE) == cal2.get(Calendar.MINUTE) &&
             cal1.get(Calendar.HOUR) == cal2.get(Calendar.HOUR) &&
             cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) &&
             cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
             cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) &&
             cal1.getClass() == cal2.getClass());
 }

}


 </source>
   
  
 
  



Checks if two date objects are on the same day ignoring time

   <source lang="java">
  

import java.math.BigDecimal; import java.math.BigInteger; import java.util.Calendar; import java.util.Date; /**

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


/**

*

A suite of utilities surrounding the use of the * {@link java.util.Calendar} and {@link java.util.Date} object.

* 
*

DateUtils contains a lot of common methods considering manipulations * of Dates or Calendars. Some methods require some extra explanation. * The truncate and round methods could be considered the Math.floor(), * Math.ceil() or Math.round versions for dates * This way date-fields will be ignored in bottom-up order. * As a complement to these methods we"ve introduced some fragment-methods. * With these methods the Date-fields will be ignored in top-down order. * Since a date without a year is not a valid date, you have to decide in what * kind of date-field you want your result, for instance milliseconds or days. *

*   
*   
*
* @author 
* @author Phil Steitz
* @author Robert Scholte
* @since 2.0
* @version $Id: DateUtils.java 634096 2008-03-06 00:58:11Z niallp $
*/

public class Main {

 //-----------------------------------------------------------------------
 /**
*

Checks if two date objects are on the same day ignoring time.

  *
*

28 Mar 2002 13:45 and 28 Mar 2002 06:01 would return true. * 28 Mar 2002 13:45 and 12 Mar 2002 13:45 would return false. *

  * 
  * @param date1  the first date, not altered, not null
  * @param date2  the second date, not altered, not null
  * @return true if they represent the same day
  * @throws IllegalArgumentException if either date is null
  * @since 2.1
  */
 public static boolean isSameDay(Date date1, Date date2) {
     if (date1 == null || date2 == null) {
         throw new IllegalArgumentException("The date must not be null");
     }
     Calendar cal1 = Calendar.getInstance();
     cal1.setTime(date1);
     Calendar cal2 = Calendar.getInstance();
     cal2.setTime(date2);
     return isSameDay(cal1, cal2);
 }
 /**
*

Checks if two calendar objects are on the same day ignoring time.

  *
*

28 Mar 2002 13:45 and 28 Mar 2002 06:01 would return true. * 28 Mar 2002 13:45 and 12 Mar 2002 13:45 would return false. *

  * 
  * @param cal1  the first calendar, not altered, not null
  * @param cal2  the second calendar, not altered, not null
  * @return true if they represent the same day
  * @throws IllegalArgumentException if either calendar is null
  * @since 2.1
  */
 public static boolean isSameDay(Calendar cal1, Calendar cal2) {
     if (cal1 == null || cal2 == null) {
         throw new IllegalArgumentException("The date must not be null");
     }
     return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) &&
             cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
             cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR));
 }

}


 </source>
   
  
 
  



Checks if two date objects represent the same instant in time

   <source lang="java">
  

import java.math.BigDecimal; import java.math.BigInteger; import java.util.Calendar; import java.util.Date; /**

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


/**

*

A suite of utilities surrounding the use of the * {@link java.util.Calendar} and {@link java.util.Date} object.

* 
*

DateUtils contains a lot of common methods considering manipulations * of Dates or Calendars. Some methods require some extra explanation. * The truncate and round methods could be considered the Math.floor(), * Math.ceil() or Math.round versions for dates * This way date-fields will be ignored in bottom-up order. * As a complement to these methods we"ve introduced some fragment-methods. * With these methods the Date-fields will be ignored in top-down order. * Since a date without a year is not a valid date, you have to decide in what * kind of date-field you want your result, for instance milliseconds or days. *

*   
*   
*
* @author 
* @author Phil Steitz
* @author Robert Scholte
* @since 2.0
* @version $Id: DateUtils.java 634096 2008-03-06 00:58:11Z niallp $
*/

public class Main {

 //-----------------------------------------------------------------------
 /**
*

Checks if two date objects represent the same instant in time.

  *
*

This method compares the long millisecond time of the two objects.

  * 
  * @param date1  the first date, not altered, not null
  * @param date2  the second date, not altered, not null
  * @return true if they represent the same millisecond instant
  * @throws IllegalArgumentException if either date is null
  * @since 2.1
  */
 public static boolean isSameInstant(Date date1, Date date2) {
     if (date1 == null || date2 == null) {
         throw new IllegalArgumentException("The date must not be null");
     }
     return date1.getTime() == date2.getTime();
 }
 /**
*

Checks if two calendar objects represent the same instant in time.

  *
*

This method compares the long millisecond time of the two objects.

  * 
  * @param cal1  the first calendar, not altered, not null
  * @param cal2  the second calendar, not altered, not null
  * @return true if they represent the same millisecond instant
  * @throws IllegalArgumentException if either date is null
  * @since 2.1
  */
 public static boolean isSameInstant(Calendar cal1, Calendar cal2) {
     if (cal1 == null || cal2 == null) {
         throw new IllegalArgumentException("The date must not be null");
     }
     return cal1.getTime().getTime() == cal2.getTime().getTime();
 }

}


 </source>
   
  
 
  



Compare Dates

   <source lang="java">
    

import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class CompareDates {

 public static void main(String[] args) throws ParseException {
   DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
   // Get Date 1
   Date d1 = df.parse("2000-02-01");
   // Get Date 2
   Date d2 = df.parse("2001-03-02");
   String relation;
   if (d1.equals(d2))
     relation = "the same date as";
   else if (d1.before(d2))
     relation = "before";
   else
     relation = "after";
   System.out.println(d1 + " is " + relation + " " + d2);
 }

}




 </source>
   
  
 
  



Compare File Dates

   <source lang="java">
    

import java.io.File; public class CompareFileDates {

 public static void main(String[] args) {
   // Get the timestamp from file 1
   String f1 = "run.bat";
   long d1 = new File(f1).lastModified();
   // Get the timestamp from file 2
   String f2 = "build.xml";
   long d2 = new File(f2).lastModified();
   String relation;
   if (d1 == d2)
     relation = "the same age as";
   else if (d1 < d2)
     relation = "older than";
   else
     relation = "newer than";
   System.out.println(f1 + " is " + relation + " " + f2);
 }

}




 </source>
   
  
 
  



Compute days between 2 dates

   <source lang="java">
    

import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class Main{

 public static void main(String args[]) {
   Calendar c1 = new GregorianCalendar();
   Calendar c2 = new GregorianCalendar();
   c1.set(2000, 12, 12, 0, 0, 0);
   c2.set(2001, 12, 12, 0, 0, 0);
   System.out.println(daysBetween(c1.getTime(), c2.getTime()) + " day(s) between " + args[0] + "-"
       + args[1] + "-" + args[2] + " and " + args[3] + "-" + args[4] + "-" + args[5]);
 }
 static final long ONE_HOUR = 60 * 60 * 1000L;
 public static long daysBetween(Date d1, Date d2) {
   return ((d2.getTime() - d1.getTime() + ONE_HOUR) / (ONE_HOUR * 24));
 }

}



 </source>
   
  
 
  



Convert Date to String

   <source lang="java">
   

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) {
   DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
   Date today = Calendar.getInstance().getTime();
   String reportDate = df.format(today);
   System.out.println("Report Date: " + reportDate);
 }

}



 </source>
   
  
 
  



Convert day of the year to date

   <source lang="java">
    

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   int dayOfYear = 112;
   Calendar calendar = Calendar.getInstance();
   calendar.set(Calendar.DAY_OF_YEAR, dayOfYear);
   System.out.println("Day of year " + dayOfYear + " = " + calendar.getTime());
 }

}



 </source>
   
  
 
  



Convert day of year to day of month

   <source lang="java">
    

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   Calendar cal = Calendar.getInstance();
   cal.set(Calendar.YEAR, 2007);
   cal.set(Calendar.DAY_OF_YEAR, 180);
   System.out.println("Calendar date is: " + cal.getTime());
   int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
   System.out.println("Calendar day of month: " + dayOfMonth);
   int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
   System.out.println("Calendar day of week: " + dayOfWeek);
 }

}




 </source>
   
  
 
  



Convert longs (time_t in UNIX terminology) to seconds

   <source lang="java">
    

/**

* Convert longs (time_t in UNIX terminology) to seconds.
*/

public class LongToMSec {

 public static void main(String[] args) {
   System.out.println(msToSecs(1000));
   System.out.println(msToSecs(1100));
   System.out.println(msToSecs(1024));
 }
 /** Convert a long ("time_t") to seconds and milliseconds */
 public static String msToSecs(long t) {
   // The first attempt fails for the case "1024"
   //return t/1000 + "." + t%1000;
   return Double.toString(t / 1000D);
 }

}




 </source>
   
  
 
  



Convert milliseconds value to date

   <source lang="java">
    

import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
   long now = System.currentTimeMillis();
   Calendar calendar = Calendar.getInstance();
   calendar.setTimeInMillis(now);
   System.out.println(now + " = " + formatter.format(calendar.getTime()));
 }

}



 </source>
   
  
 
  



Convert string date to long value

   <source lang="java">
   

import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class Main {

 public static void main(String[] args) throws Exception {
   String today = "21/12/2007";
   DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
   Date date = formatter.parse(today);
   long dateInLong = date.getTime();
   System.out.println("date = " + date);
   System.out.println("dateInLong = " + dateInLong);
 }

}



 </source>
   
  
 
  



Create a Date object using the Calendar class

   <source lang="java">
    

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   int year = 2009;
   int month = 0; // January
   int date = 1;
   Calendar cal = Calendar.getInstance();
   cal.clear();
   cal.set(Calendar.YEAR, year);
   cal.set(Calendar.MONTH, month);
   cal.set(Calendar.DATE, date);
   java.util.Date utilDate = cal.getTime();
   System.out.println(utilDate);
 }

} //2009-01-01



 </source>
   
  
 
  



Create SimpleDateFormats from a string read from a file

   <source lang="java">
    

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.text.SimpleDateFormat; import java.util.Date; /** Create SimpleDateFormats from a string read from a file */ public class DateFormatFile {

 /** Today"s Date */
 Date dNow = new Date();
 public static void main(String[] args) throws IOException {
   DateFormatFile df = new DateFormatFile();
   BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
   String line;
   while ((line = is.readLine()) != null) {
     df.process(line);
   }
 }
 /** Use a SimpleDateFormat - based on arg - to print the date your way. */
 protected void process(String arg) {
   SimpleDateFormat formatter = new SimpleDateFormat(arg);
   System.out.println("FORMAT: " + arg);
   System.out.println("RESULT: " + formatter.format(dNow));
   System.out.println();
 }

}




 </source>
   
  
 
  



DateAdd -- compute the difference between two dates

   <source lang="java">
    

import java.util.Date; /**

* DateAdd -- compute the difference between two dates.
*/

public class DateAdd {

 public static void main(String[] av) {
   //+
   /** Today"s date */
   Date now = new Date();
   long t = now.getTime();
   t -= 700 * 24 * 60 * 60 * 1000;
   Date then = new Date(t);
   System.out.println("Seven hundred days ago was " + then);
   //-
 }

}




 </source>
   
  
 
  



Date and time formatting utilities and constants.

   <source lang="java">
  

/*

* 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.io.IOException; import java.io.ObjectInputStream; import java.text.DateFormat; import java.text.DateFormatSymbols; import java.text.FieldPosition; import java.text.Format; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /**

*

Date and time formatting utilities and constants.

*
*

Formatting is performed using the * {@link org.apache.rumons.lang.time.FastDateFormat} class.

*
* @author Apache Ant - DateUtils
* @author 
* @since 2.0
* @version $Id: DateFormatUtils.java 615243 2008-01-25 15:20:32Z niallp $
*/

public class DateFormatUtils {

   /**
    * ISO8601 formatter for date-time without time zone.
    * The format used is yyyy-MM-dd"T"HH:mm:ss.
    */
   public static final FastDateFormat ISO_DATETIME_FORMAT
           = FastDateFormat.getInstance("yyyy-MM-dd"T"HH:mm:ss");
   /**
    * ISO8601 formatter for date-time with time zone.
    * The format used is yyyy-MM-dd"T"HH:mm:ssZZ.
    */
   public static final FastDateFormat ISO_DATETIME_TIME_ZONE_FORMAT
           = FastDateFormat.getInstance("yyyy-MM-dd"T"HH:mm:ssZZ");
   /**
    * ISO8601 formatter for date without time zone.
    * The format used is yyyy-MM-dd.
    */
   public static final FastDateFormat ISO_DATE_FORMAT
           = FastDateFormat.getInstance("yyyy-MM-dd");
   /**
    * ISO8601-like formatter for date with time zone.
    * The format used is yyyy-MM-ddZZ.
    * This pattern does not comply with the formal ISO8601 specification
    * as the standard does not allow a time zone  without a time.
    */
   public static final FastDateFormat ISO_DATE_TIME_ZONE_FORMAT
           = FastDateFormat.getInstance("yyyy-MM-ddZZ");
   /**
    * ISO8601 formatter for time without time zone.
    * The format used is "T"HH:mm:ss.
    */
   public static final FastDateFormat ISO_TIME_FORMAT
           = FastDateFormat.getInstance(""T"HH:mm:ss");
   /**
    * ISO8601 formatter for time with time zone.
    * The format used is "T"HH:mm:ssZZ.
    */
   public static final FastDateFormat ISO_TIME_TIME_ZONE_FORMAT
           = FastDateFormat.getInstance(""T"HH:mm:ssZZ");
   /**
    * ISO8601-like formatter for time without time zone.
    * The format used is HH:mm:ss.
    * This pattern does not comply with the formal ISO8601 specification
    * as the standard requires the "T" prefix for times.
    */
   public static final FastDateFormat ISO_TIME_NO_T_FORMAT
           = FastDateFormat.getInstance("HH:mm:ss");
   /**
    * ISO8601-like formatter for time with time zone.
    * The format used is HH:mm:ssZZ.
    * This pattern does not comply with the formal ISO8601 specification
    * as the standard requires the "T" prefix for times.
    */
   public static final FastDateFormat ISO_TIME_NO_T_TIME_ZONE_FORMAT
           = FastDateFormat.getInstance("HH:mm:ssZZ");
   /**
    * SMTP (and probably other) date headers.
    * The format used is EEE, dd MMM yyyy HH:mm:ss Z in US locale.
    */
   public static final FastDateFormat SMTP_DATETIME_FORMAT
           = FastDateFormat.getInstance("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US);
   //-----------------------------------------------------------------------
   /**
*

DateFormatUtils instances should NOT be constructed in standard programming.

    *
*

This constructor is public to permit tools that require a JavaBean instance * to operate.

    */
   public DateFormatUtils() {
       super();
   }
   /**
*

Formats a date/time into a specific pattern using the UTC time zone.

    * 
    * @param millis  the date to format expressed in milliseconds
    * @param pattern  the pattern to use to format the date
    * @return the formatted date
    */
   public static String formatUTC(long millis, String pattern) {
       return format(new Date(millis), pattern, UTC_TIME_ZONE, null);
   }
   /**
*

Formats a date/time into a specific pattern using the UTC time zone.

    * 
    * @param date  the date to format
    * @param pattern  the pattern to use to format the date
    * @return the formatted date
    */
   public static String formatUTC(Date date, String pattern) {
       return format(date, pattern, UTC_TIME_ZONE, null);
   }
   
   /**
*

Formats a date/time into a specific pattern using the UTC time zone.

    * 
    * @param millis  the date to format expressed in milliseconds
    * @param pattern  the pattern to use to format the date
    * @param locale  the locale to use, may be null
    * @return the formatted date
    */
   public static String formatUTC(long millis, String pattern, Locale locale) {
       return format(new Date(millis), pattern, UTC_TIME_ZONE, locale);
   }
   public static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("GMT");
   /**
*

Formats a date/time into a specific pattern using the UTC time zone.

    * 
    * @param date  the date to format
    * @param pattern  the pattern to use to format the date
    * @param locale  the locale to use, may be null
    * @return the formatted date
    */
   public static String formatUTC(Date date, String pattern, Locale locale) {
       return format(date, pattern, UTC_TIME_ZONE, locale);
   }
   
   /**
*

Formats a date/time into a specific pattern.

    * 
    * @param millis  the date to format expressed in milliseconds
    * @param pattern  the pattern to use to format the date
    * @return the formatted date
    */
   public static String format(long millis, String pattern) {
       return format(new Date(millis), pattern, null, null);
   }
   /**
*

Formats a date/time into a specific pattern.

    * 
    * @param date  the date to format
    * @param pattern  the pattern to use to format the date
    * @return the formatted date
    */
   public static String format(Date date, String pattern) {
       return format(date, pattern, null, null);
   }
   /**
*

Formats a calendar into a specific pattern.

    * 
    * @param calendar  the calendar to format
    * @param pattern  the pattern to use to format the calendar
    * @return the formatted calendar
    * @see FastDateFormat#format(Calendar)
    * @since 2.4
    */
   public static String format(Calendar calendar, String pattern) {
       return format(calendar, pattern, null, null);
   }
   
   /**
*

Formats a date/time into a specific pattern in a time zone.

    * 
    * @param millis  the time expressed in milliseconds
    * @param pattern  the pattern to use to format the date
    * @param timeZone  the time zone  to use, may be null
    * @return the formatted date
    */
   public static String format(long millis, String pattern, TimeZone timeZone) {
       return format(new Date(millis), pattern, timeZone, null);
   }
   /**
*

Formats a date/time into a specific pattern in a time zone.

    * 
    * @param date  the date to format
    * @param pattern  the pattern to use to format the date
    * @param timeZone  the time zone  to use, may be null
    * @return the formatted date
    */
   public static String format(Date date, String pattern, TimeZone timeZone) {
       return format(date, pattern, timeZone, null);
   }
   /**
*

Formats a calendar into a specific pattern in a time zone.

    * 
    * @param calendar  the calendar to format
    * @param pattern  the pattern to use to format the calendar
    * @param timeZone  the time zone  to use, may be null
    * @return the formatted calendar
    * @see FastDateFormat#format(Calendar)
    * @since 2.4
    */
   public static String format(Calendar calendar, String pattern, TimeZone timeZone) {
       return format(calendar, pattern, timeZone, null);
   }
   /**
*

Formats a date/time into a specific pattern in a locale.

    * 
    * @param millis  the date to format expressed in milliseconds
    * @param pattern  the pattern to use to format the date
    * @param locale  the locale to use, may be null
    * @return the formatted date
    */
   public static String format(long millis, String pattern, Locale locale) {
       return format(new Date(millis), pattern, null, locale);
   }
   /**
*

Formats a date/time into a specific pattern in a locale.

    * 
    * @param date  the date to format
    * @param pattern  the pattern to use to format the date
    * @param locale  the locale to use, may be null
    * @return the formatted date
    */
   public static String format(Date date, String pattern, Locale locale) {
       return format(date, pattern, null, locale);
   }
   /**
*

Formats a calendar into a specific pattern in a locale.

    * 
    * @param calendar  the calendar to format
    * @param pattern  the pattern to use to format the calendar
    * @param locale  the locale to use, may be null
    * @return the formatted calendar
    * @see FastDateFormat#format(Calendar)
    * @since 2.4
    */
   public static String format(Calendar calendar, String pattern, Locale locale) {
       return format(calendar, pattern, null, locale);
   }
   /**
*

Formats a date/time into a specific pattern in a time zone and locale.

    * 
    * @param millis  the date to format expressed in milliseconds
    * @param pattern  the pattern to use to format the date
    * @param timeZone  the time zone  to use, may be null
    * @param locale  the locale to use, may be null
    * @return the formatted date
    */
   public static String format(long millis, String pattern, TimeZone timeZone, Locale locale) {
       return format(new Date(millis), pattern, timeZone, locale);
   }
   /**
*

Formats a date/time into a specific pattern in a time zone and locale.

    * 
    * @param date  the date to format
    * @param pattern  the pattern to use to format the date
    * @param timeZone  the time zone  to use, may be null
    * @param locale  the locale to use, may be null
    * @return the formatted date
    */
   public static String format(Date date, String pattern, TimeZone timeZone, Locale locale) {
       FastDateFormat df = FastDateFormat.getInstance(pattern, timeZone, locale);
       return df.format(date);
   }
   /**
*

Formats a calendar into a specific pattern in a time zone and locale.

    * 
    * @param calendar  the calendar to format
    * @param pattern  the pattern to use to format the calendar
    * @param timeZone  the time zone  to use, may be null
    * @param locale  the locale to use, may be null
    * @return the formatted calendar
    * @see FastDateFormat#format(Calendar)
    * @since 2.4
    */
   public static String format(Calendar calendar, String pattern, TimeZone timeZone, Locale locale) {
       FastDateFormat df = FastDateFormat.getInstance(pattern, timeZone, locale);
       return df.format(calendar);
   }

} /*

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

/**

*

FastDateFormat is a fast and thread-safe version of * {@link java.text.SimpleDateFormat}.

* 
*

This class can be used as a direct replacement to * SimpleDateFormat in most formatting situations. * This class is especially useful in multi-threaded server environments. * SimpleDateFormat is not thread-safe in any JDK version, * nor will it be as Sun have closed the bug/RFE. *

*
*

Only formatting is supported, but all patterns are compatible with * SimpleDateFormat (except time zones - see below).

*
*

Java 1.4 introduced a new pattern letter, "Z", to represent * time zones in RFC822 format (eg. +0800 or -1100). * This pattern letter can be used here (on all JDK versions).

*
*

In addition, the pattern "ZZ" has been made to represent * ISO8601 full format time zones (eg. +08:00 or -11:00). * This introduces a minor incompatibility with Java 1.4, but at a gain of * useful functionality.

*
* @author TeaTrove project
* @author Brian S O"Neill
* @author Sean Schofield
* @author Gary Gregory
* @author Stephen Colebourne
* @author Nikolay Metchev
* @since 2.0
* @version $Id: FastDateFormat.java 590552 2007-10-31 04:04:32Z bayard $
*/
class FastDateFormat extends Format {
   // A lot of the speed in this class comes from caching, but some comes
   // from the special int to StringBuffer conversion.
   //
   // The following produces a padded 2 digit number:
   //   buffer.append((char)(value / 10 + "0"));
   //   buffer.append((char)(value % 10 + "0"));
   //
   // Note that the fastest append to StringBuffer is a single char (used here).
   // Note that Integer.toString() is not called, the conversion is simply
   // taking the value and adding (mathematically) the ASCII value for "0".
   // So, don"t change this code! It works and is very fast.
   
   /**
    * Required for serialization support.
    * 
    * @see java.io.Serializable
    */
   private static final long serialVersionUID = 1L;
   /**
    * FULL locale dependent date or time style.
    */
   public static final int FULL = DateFormat.FULL;
   /**
    * LONG locale dependent date or time style.
    */
   public static final int LONG = DateFormat.LONG;
   /**
    * MEDIUM locale dependent date or time style.
    */
   public static final int MEDIUM = DateFormat.MEDIUM;
   /**
    * SHORT locale dependent date or time style.
    */
   public static final int SHORT = DateFormat.SHORT;
   
   private static String cDefaultPattern;
   private static final Map cInstanceCache = new HashMap(7);
   private static final Map cDateInstanceCache = new HashMap(7);
   private static final Map cTimeInstanceCache = new HashMap(7);
   private static final Map cDateTimeInstanceCache = new HashMap(7);
   private static final Map cTimeZoneDisplayCache = new HashMap(7);
   /**
    * The pattern.
    */
   private final String mPattern;
   /**
    * The time zone.
    */
   private final TimeZone mTimeZone;
   /**
    * Whether the time zone overrides any on Calendars.
    */
   private final boolean mTimeZoneForced;
   /**
    * The locale.
    */
   private final Locale mLocale;
   /**
    * Whether the locale overrides the default.
    */
   private final boolean mLocaleForced;
   /**
    * The parsed rules.
    */
   private transient Rule[] mRules;
   /**
    * The estimated maximum length.
    */
   private transient int mMaxLengthEstimate;
   //-----------------------------------------------------------------------
   /**
*

Gets a formatter instance using the default pattern in the * default locale.

    * 
    * @return a date/time formatter
    */
   public static FastDateFormat getInstance() {
       return getInstance(getDefaultPattern(), null, null);
   }
   /**
*

Gets a formatter instance using the specified pattern in the * default locale.

    * 
    * @param pattern  {@link java.text.SimpleDateFormat} compatible
    *  pattern
    * @return a pattern based date/time formatter
    * @throws IllegalArgumentException if pattern is invalid
    */
   public static FastDateFormat getInstance(String pattern) {
       return getInstance(pattern, null, null);
   }
   /**
*

Gets a formatter instance using the specified pattern and * time zone.

    * 
    * @param pattern  {@link java.text.SimpleDateFormat} compatible
    *  pattern
    * @param timeZone  optional time zone, overrides time zone of
    *  formatted date
    * @return a pattern based date/time formatter
    * @throws IllegalArgumentException if pattern is invalid
    */
   public static FastDateFormat getInstance(String pattern, TimeZone timeZone) {
       return getInstance(pattern, timeZone, null);
   }
   /**
*

Gets a formatter instance using the specified pattern and * locale.

    * 
    * @param pattern  {@link java.text.SimpleDateFormat} compatible
    *  pattern
    * @param locale  optional locale, overrides system locale
    * @return a pattern based date/time formatter
    * @throws IllegalArgumentException if pattern is invalid
    */
   public static FastDateFormat getInstance(String pattern, Locale locale) {
       return getInstance(pattern, null, locale);
   }
   /**
*

Gets a formatter instance using the specified pattern, time zone * and locale.

    * 
    * @param pattern  {@link java.text.SimpleDateFormat} compatible
    *  pattern
    * @param timeZone  optional time zone, overrides time zone of
    *  formatted date
    * @param locale  optional locale, overrides system locale
    * @return a pattern based date/time formatter
    * @throws IllegalArgumentException if pattern is invalid
    *  or null
    */
   public static synchronized FastDateFormat getInstance(String pattern, TimeZone timeZone, Locale locale) {
       FastDateFormat emptyFormat = new FastDateFormat(pattern, timeZone, locale);
       FastDateFormat format = (FastDateFormat) cInstanceCache.get(emptyFormat);
       if (format == null) {
           format = emptyFormat;
           format.init();  // convert shell format into usable one
           cInstanceCache.put(format, format);  // this is OK!
       }
       return format;
   }
   //-----------------------------------------------------------------------
   /**
*

Gets a date formatter instance using the specified style in the * default time zone and locale.

    * 
    * @param style  date style: FULL, LONG, MEDIUM, or SHORT
    * @return a localized standard date formatter
    * @throws IllegalArgumentException if the Locale has no date
    *  pattern defined
    * @since 2.1
    */
   public static FastDateFormat getDateInstance(int style) {
       return getDateInstance(style, null, null);
   }
   /**
*

Gets a date formatter instance using the specified style and * locale in the default time zone.

    * 
    * @param style  date style: FULL, LONG, MEDIUM, or SHORT
    * @param locale  optional locale, overrides system locale
    * @return a localized standard date formatter
    * @throws IllegalArgumentException if the Locale has no date
    *  pattern defined
    * @since 2.1
    */
   public static FastDateFormat getDateInstance(int style, Locale locale) {
       return getDateInstance(style, null, locale);
   }
   /**
*

Gets a date formatter instance using the specified style and * time zone in the default locale.

    * 
    * @param style  date style: FULL, LONG, MEDIUM, or SHORT
    * @param timeZone  optional time zone, overrides time zone of
    *  formatted date
    * @return a localized standard date formatter
    * @throws IllegalArgumentException if the Locale has no date
    *  pattern defined
    * @since 2.1
    */
   public static FastDateFormat getDateInstance(int style, TimeZone timeZone) {
       return getDateInstance(style, timeZone, null);
   }
   /**
*

Gets a date formatter instance using the specified style, time * zone and locale.

    * 
    * @param style  date style: FULL, LONG, MEDIUM, or SHORT
    * @param timeZone  optional time zone, overrides time zone of
    *  formatted date
    * @param locale  optional locale, overrides system locale
    * @return a localized standard date formatter
    * @throws IllegalArgumentException if the Locale has no date
    *  pattern defined
    */
   public static synchronized FastDateFormat getDateInstance(int style, TimeZone timeZone, Locale locale) {
       Object key = new Integer(style);
       if (timeZone != null) {
           key = new Pair(key, timeZone);
       }
       if (locale == null) {
           locale = Locale.getDefault();
       }
       key = new Pair(key, locale);
       FastDateFormat format = (FastDateFormat) cDateInstanceCache.get(key);
       if (format == null) {
           try {
               SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getDateInstance(style, locale);
               String pattern = formatter.toPattern();
               format = getInstance(pattern, timeZone, locale);
               cDateInstanceCache.put(key, format);
               
           } catch (ClassCastException ex) {
               throw new IllegalArgumentException("No date pattern for locale: " + locale);
           }
       }
       return format;
   }
   //-----------------------------------------------------------------------
   /**
*

Gets a time formatter instance using the specified style in the * default time zone and locale.

    * 
    * @param style  time style: FULL, LONG, MEDIUM, or SHORT
    * @return a localized standard time formatter
    * @throws IllegalArgumentException if the Locale has no time
    *  pattern defined
    * @since 2.1
    */
   public static FastDateFormat getTimeInstance(int style) {
       return getTimeInstance(style, null, null);
   }
   /**
*

Gets a time formatter instance using the specified style and * locale in the default time zone.

    * 
    * @param style  time style: FULL, LONG, MEDIUM, or SHORT
    * @param locale  optional locale, overrides system locale
    * @return a localized standard time formatter
    * @throws IllegalArgumentException if the Locale has no time
    *  pattern defined
    * @since 2.1
    */
   public static FastDateFormat getTimeInstance(int style, Locale locale) {
       return getTimeInstance(style, null, locale);
   }
   
   /**
*

Gets a time formatter instance using the specified style and * time zone in the default locale.

    * 
    * @param style  time style: FULL, LONG, MEDIUM, or SHORT
    * @param timeZone  optional time zone, overrides time zone of
    *  formatted time
    * @return a localized standard time formatter
    * @throws IllegalArgumentException if the Locale has no time
    *  pattern defined
    * @since 2.1
    */
   public static FastDateFormat getTimeInstance(int style, TimeZone timeZone) {
       return getTimeInstance(style, timeZone, null);
   }
   
   /**
*

Gets a time formatter instance using the specified style, time * zone and locale.

    * 
    * @param style  time style: FULL, LONG, MEDIUM, or SHORT
    * @param timeZone  optional time zone, overrides time zone of
    *  formatted time
    * @param locale  optional locale, overrides system locale
    * @return a localized standard time formatter
    * @throws IllegalArgumentException if the Locale has no time
    *  pattern defined
    */
   public static synchronized FastDateFormat getTimeInstance(int style, TimeZone timeZone, Locale locale) {
       Object key = new Integer(style);
       if (timeZone != null) {
           key = new Pair(key, timeZone);
       }
       if (locale != null) {
           key = new Pair(key, locale);
       }
       FastDateFormat format = (FastDateFormat) cTimeInstanceCache.get(key);
       if (format == null) {
           if (locale == null) {
               locale = Locale.getDefault();
           }
           try {
               SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getTimeInstance(style, locale);
               String pattern = formatter.toPattern();
               format = getInstance(pattern, timeZone, locale);
               cTimeInstanceCache.put(key, format);
           
           } catch (ClassCastException ex) {
               throw new IllegalArgumentException("No date pattern for locale: " + locale);
           }
       }
       return format;
   }
   //-----------------------------------------------------------------------
   /**
*

Gets a date/time formatter instance using the specified style * in the default time zone and locale.

    * 
    * @param dateStyle  date style: FULL, LONG, MEDIUM, or SHORT
    * @param timeStyle  time style: FULL, LONG, MEDIUM, or SHORT
    * @return a localized standard date/time formatter
    * @throws IllegalArgumentException if the Locale has no date/time
    *  pattern defined
    * @since 2.1
    */
   public static FastDateFormat getDateTimeInstance(
           int dateStyle, int timeStyle) {
       return getDateTimeInstance(dateStyle, timeStyle, null, null);
   }
   
   /**
*

Gets a date/time formatter instance using the specified style and * locale in the default time zone.

    * 
    * @param dateStyle  date style: FULL, LONG, MEDIUM, or SHORT
    * @param timeStyle  time style: FULL, LONG, MEDIUM, or SHORT
    * @param locale  optional locale, overrides system locale
    * @return a localized standard date/time formatter
    * @throws IllegalArgumentException if the Locale has no date/time
    *  pattern defined
    * @since 2.1
    */
   public static FastDateFormat getDateTimeInstance(
           int dateStyle, int timeStyle, Locale locale) {
       return getDateTimeInstance(dateStyle, timeStyle, null, locale);
   }
   
   /**
*

Gets a date/time formatter instance using the specified style and * time zone in the default locale.

    * 
    * @param dateStyle  date style: FULL, LONG, MEDIUM, or SHORT
    * @param timeStyle  time style: FULL, LONG, MEDIUM, or SHORT
    * @param timeZone  optional time zone, overrides time zone of
    *  formatted date
    * @return a localized standard date/time formatter
    * @throws IllegalArgumentException if the Locale has no date/time
    *  pattern defined
    * @since 2.1
    */
   public static FastDateFormat getDateTimeInstance(
           int dateStyle, int timeStyle, TimeZone timeZone) {
       return getDateTimeInstance(dateStyle, timeStyle, timeZone, null);
   }    
   /**
*

Gets a date/time formatter instance using the specified style, * time zone and locale.

    * 
    * @param dateStyle  date style: FULL, LONG, MEDIUM, or SHORT
    * @param timeStyle  time style: FULL, LONG, MEDIUM, or SHORT
    * @param timeZone  optional time zone, overrides time zone of
    *  formatted date
    * @param locale  optional locale, overrides system locale
    * @return a localized standard date/time formatter
    * @throws IllegalArgumentException if the Locale has no date/time
    *  pattern defined
    */
   public static synchronized FastDateFormat getDateTimeInstance(int dateStyle, int timeStyle, TimeZone timeZone,
           Locale locale) {
       Object key = new Pair(new Integer(dateStyle), new Integer(timeStyle));
       if (timeZone != null) {
           key = new Pair(key, timeZone);
       }
       if (locale == null) {
           locale = Locale.getDefault();
       }
       key = new Pair(key, locale);
       FastDateFormat format = (FastDateFormat) cDateTimeInstanceCache.get(key);
       if (format == null) {
           try {
               SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getDateTimeInstance(dateStyle, timeStyle,
                       locale);
               String pattern = formatter.toPattern();
               format = getInstance(pattern, timeZone, locale);
               cDateTimeInstanceCache.put(key, format);
           } catch (ClassCastException ex) {
               throw new IllegalArgumentException("No date time pattern for locale: " + locale);
           }
       }
       return format;
   }
   //-----------------------------------------------------------------------
   /**
*

Gets the time zone display name, using a cache for performance.

    * 
    * @param tz  the zone to query
    * @param daylight  true if daylight savings
    * @param style  the style to use TimeZone.LONG
    *  or TimeZone.SHORT
    * @param locale  the locale to use
    * @return the textual name of the time zone
    */
   static synchronized String getTimeZoneDisplay(TimeZone tz, boolean daylight, int style, Locale locale) {
       Object key = new TimeZoneDisplayKey(tz, daylight, style, locale);
       String value = (String) cTimeZoneDisplayCache.get(key);
       if (value == null) {
           // This is a very slow call, so cache the results.
           value = tz.getDisplayName(daylight, style, locale);
           cTimeZoneDisplayCache.put(key, value);
       }
       return value;
   }
   /**
*

Gets the default pattern.

    * 
    * @return the default pattern
    */
   private static synchronized String getDefaultPattern() {
       if (cDefaultPattern == null) {
           cDefaultPattern = new SimpleDateFormat().toPattern();
       }
       return cDefaultPattern;
   }
   // Constructor
   //-----------------------------------------------------------------------
   /**
*

Constructs a new FastDateFormat.

    * 
    * @param pattern  {@link java.text.SimpleDateFormat} compatible
    *  pattern
    * @param timeZone  time zone to use, null means use
    *  default for Date and value within for
    *  Calendar
    * @param locale  locale, null means use system
    *  default
    * @throws IllegalArgumentException if pattern is invalid or
    *  null
    */
   protected FastDateFormat(String pattern, TimeZone timeZone, Locale locale) {
       super();
       if (pattern == null) {
           throw new IllegalArgumentException("The pattern must not be null");
       }
       mPattern = pattern;
       
       mTimeZoneForced = (timeZone != null);
       if (timeZone == null) {
           timeZone = TimeZone.getDefault();
       }
       mTimeZone = timeZone;
       
       mLocaleForced = (locale != null);
       if (locale == null) {
           locale = Locale.getDefault();
       }
       mLocale = locale;
   }
   /**
*

Initializes the instance for first use.

    */
   protected void init() {
       List rulesList = parsePattern();
       mRules = (Rule[]) rulesList.toArray(new Rule[rulesList.size()]);
       int len = 0;
       for (int i=mRules.length; --i >= 0; ) {
           len += mRules[i].estimateLength();
       }
       mMaxLengthEstimate = len;
   }
   // Parse the pattern
   //-----------------------------------------------------------------------
   /**
*

Returns a list of Rules given a pattern.

    * 
    * @return a List of Rule objects
    * @throws IllegalArgumentException if pattern is invalid
    */
   protected List parsePattern() {
       DateFormatSymbols symbols = new DateFormatSymbols(mLocale);
       List rules = new ArrayList();
       String[] ERAs = symbols.getEras();
       String[] months = symbols.getMonths();
       String[] shortMonths = symbols.getShortMonths();
       String[] weekdays = symbols.getWeekdays();
       String[] shortWeekdays = symbols.getShortWeekdays();
       String[] AmPmStrings = symbols.getAmPmStrings();
       int length = mPattern.length();
       int[] indexRef = new int[1];
       for (int i = 0; i < length; i++) {
           indexRef[0] = i;
           String token = parseToken(mPattern, indexRef);
           i = indexRef[0];
           int tokenLen = token.length();
           if (tokenLen == 0) {
               break;
           }
           Rule rule;
           char c = token.charAt(0);
           switch (c) {
           case "G": // era designator (text)
               rule = new TextField(Calendar.ERA, ERAs);
               break;
           case "y": // year (number)
               if (tokenLen >= 4) {
                   rule = selectNumberRule(Calendar.YEAR, tokenLen);
               } else {
                   rule = TwoDigitYearField.INSTANCE;
               }
               break;
           case "M": // month in year (text and number)
               if (tokenLen >= 4) {
                   rule = new TextField(Calendar.MONTH, months);
               } else if (tokenLen == 3) {
                   rule = new TextField(Calendar.MONTH, shortMonths);
               } else if (tokenLen == 2) {
                   rule = TwoDigitMonthField.INSTANCE;
               } else {
                   rule = UnpaddedMonthField.INSTANCE;
               }
               break;
           case "d": // day in month (number)
               rule = selectNumberRule(Calendar.DAY_OF_MONTH, tokenLen);
               break;
           case "h": // hour in am/pm (number, 1..12)
               rule = new TwelveHourField(selectNumberRule(Calendar.HOUR, tokenLen));
               break;
           case "H": // hour in day (number, 0..23)
               rule = selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen);
               break;
           case "m": // minute in hour (number)
               rule = selectNumberRule(Calendar.MINUTE, tokenLen);
               break;
           case "s": // second in minute (number)
               rule = selectNumberRule(Calendar.SECOND, tokenLen);
               break;
           case "S": // millisecond (number)
               rule = selectNumberRule(Calendar.MILLISECOND, tokenLen);
               break;
           case "E": // day in week (text)
               rule = new TextField(Calendar.DAY_OF_WEEK, tokenLen < 4 ? shortWeekdays : weekdays);
               break;
           case "D": // day in year (number)
               rule = selectNumberRule(Calendar.DAY_OF_YEAR, tokenLen);
               break;
           case "F": // day of week in month (number)
               rule = selectNumberRule(Calendar.DAY_OF_WEEK_IN_MONTH, tokenLen);
               break;
           case "w": // week in year (number)
               rule = selectNumberRule(Calendar.WEEK_OF_YEAR, tokenLen);
               break;
           case "W": // week in month (number)
               rule = selectNumberRule(Calendar.WEEK_OF_MONTH, tokenLen);
               break;
           case "a": // am/pm marker (text)
               rule = new TextField(Calendar.AM_PM, AmPmStrings);
               break;
           case "k": // hour in day (1..24)
               rule = new TwentyFourHourField(selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen));
               break;
           case "K": // hour in am/pm (0..11)
               rule = selectNumberRule(Calendar.HOUR, tokenLen);
               break;
           case "z": // time zone (text)
               if (tokenLen >= 4) {
                   rule = new TimeZoneNameRule(mTimeZone, mTimeZoneForced, mLocale, TimeZone.LONG);
               } else {
                   rule = new TimeZoneNameRule(mTimeZone, mTimeZoneForced, mLocale, TimeZone.SHORT);
               }
               break;
           case "Z": // time zone (value)
               if (tokenLen == 1) {
                   rule = TimeZoneNumberRule.INSTANCE_NO_COLON;
               } else {
                   rule = TimeZoneNumberRule.INSTANCE_COLON;
               }
               break;
           case "\"": // literal text
               String sub = token.substring(1);
               if (sub.length() == 1) {
                   rule = new CharacterLiteral(sub.charAt(0));
               } else {
                   rule = new StringLiteral(sub);
               }
               break;
           default:
               throw new IllegalArgumentException("Illegal pattern component: " + token);
           }
           rules.add(rule);
       }
       return rules;
   }
   /**
*

Performs the parsing of tokens.

    * 
    * @param pattern  the pattern
    * @param indexRef  index references
    * @return parsed token
    */
   protected String parseToken(String pattern, int[] indexRef) {
       StringBuffer buf = new StringBuffer();
       int i = indexRef[0];
       int length = pattern.length();
       char c = pattern.charAt(i);
       if (c >= "A" && c <= "Z" || c >= "a" && c <= "z") {
           // Scan a run of the same character, which indicates a time
           // pattern.
           buf.append(c);
           while (i + 1 < length) {
               char peek = pattern.charAt(i + 1);
               if (peek == c) {
                   buf.append(c);
                   i++;
               } else {
                   break;
               }
           }
       } else {
           // This will identify token as text.
           buf.append("\"");
           boolean inLiteral = false;
           for (; i < length; i++) {
               c = pattern.charAt(i);
               if (c == "\"") {
                   if (i + 1 < length && pattern.charAt(i + 1) == "\"") {
                       // "" is treated as escaped "
                       i++;
                       buf.append(c);
                   } else {
                       inLiteral = !inLiteral;
                   }
               } else if (!inLiteral &&
                        (c >= "A" && c <= "Z" || c >= "a" && c <= "z")) {
                   i--;
                   break;
               } else {
                   buf.append(c);
               }
           }
       }
       indexRef[0] = i;
       return buf.toString();
   }
   /**
*

Gets an appropriate rule for the padding required.

    * 
    * @param field  the field to get a rule for
    * @param padding  the padding required
    * @return a new rule with the correct padding
    */
   protected NumberRule selectNumberRule(int field, int padding) {
       switch (padding) {
       case 1:
           return new UnpaddedNumberField(field);
       case 2:
           return new TwoDigitNumberField(field);
       default:
           return new PaddedNumberField(field, padding);
       }
   }
   // Format methods
   //-----------------------------------------------------------------------
   /**
*

Formats a Date, Calendar or * Long (milliseconds) object.

    * 
    * @param obj  the object to format
    * @param toAppendTo  the buffer to append to
    * @param pos  the position - ignored
    * @return the buffer passed in
    */
   public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
       if (obj instanceof Date) {
           return format((Date) obj, toAppendTo);
       } else if (obj instanceof Calendar) {
           return format((Calendar) obj, toAppendTo);
       } else if (obj instanceof Long) {
           return format(((Long) obj).longValue(), toAppendTo);
       } else {
           throw new IllegalArgumentException("Unknown class: " +
               (obj == null ? "<null>" : obj.getClass().getName()));
       }
   }
   /**
*

Formats a millisecond long value.

    * 
    * @param millis  the millisecond value to format
    * @return the formatted string
    * @since 2.1
    */
   public String format(long millis) {
       return format(new Date(millis));
   }
   /**
*

Formats a Date object.

    * 
    * @param date  the date to format
    * @return the formatted string
    */
   public String format(Date date) {
       Calendar c = new GregorianCalendar(mTimeZone);
       c.setTime(date);
       return applyRules(c, new StringBuffer(mMaxLengthEstimate)).toString();
   }
   /**
*

Formats a Calendar object.

    * 
    * @param calendar  the calendar to format
    * @return the formatted string
    */
   public String format(Calendar calendar) {
       return format(calendar, new StringBuffer(mMaxLengthEstimate)).toString();
   }
   /**
*

Formats a milliseond long value into the * supplied StringBuffer.

    * 
    * @param millis  the millisecond value to format
    * @param buf  the buffer to format into
    * @return the specified string buffer
    * @since 2.1
    */
   public StringBuffer format(long millis, StringBuffer buf) {
       return format(new Date(millis), buf);
   }
   /**
*

Formats a Date object into the * supplied StringBuffer.

    * 
    * @param date  the date to format
    * @param buf  the buffer to format into
    * @return the specified string buffer
    */
   public StringBuffer format(Date date, StringBuffer buf) {
       Calendar c = new GregorianCalendar(mTimeZone);
       c.setTime(date);
       return applyRules(c, buf);
   }
   /**
*

Formats a Calendar object into the * supplied StringBuffer.

    * 
    * @param calendar  the calendar to format
    * @param buf  the buffer to format into
    * @return the specified string buffer
    */
   public StringBuffer format(Calendar calendar, StringBuffer buf) {
       if (mTimeZoneForced) {
           calendar = (Calendar) calendar.clone();
           calendar.setTimeZone(mTimeZone);
       }
       return applyRules(calendar, buf);
   }
   /**
*

Performs the formatting by applying the rules to the * specified calendar.

    * 
    * @param calendar  the calendar to format
    * @param buf  the buffer to format into
    * @return the specified string buffer
    */
   protected StringBuffer applyRules(Calendar calendar, StringBuffer buf) {
       Rule[] rules = mRules;
       int len = mRules.length;
       for (int i = 0; i < len; i++) {
           rules[i].appendTo(buf, calendar);
       }
       return buf;
   }
   // Parsing
   //-----------------------------------------------------------------------
   /**
*

Parsing is not supported.

    * 
    * @param source  the string to parse
    * @param pos  the parsing position
    * @return null as not supported
    */
   public Object parseObject(String source, ParsePosition pos) {
       pos.setIndex(0);
       pos.setErrorIndex(0);
       return null;
   }
   
   // Accessors
   //-----------------------------------------------------------------------
   /**
*

Gets the pattern used by this formatter.

    * 
    * @return the pattern, {@link java.text.SimpleDateFormat} compatible
    */
   public String getPattern() {
       return mPattern;
   }
   /**
*

Gets the time zone used by this formatter.

    *
*

This zone is always used for Date formatting. * If a Calendar is passed in to be formatted, the * time zone on that may be used depending on * {@link #getTimeZoneOverridesCalendar()}.

    * 
    * @return the time zone
    */
   public TimeZone getTimeZone() {
       return mTimeZone;
   }
   /**
*

Returns true if the time zone of the * calendar overrides the time zone of the formatter.

    * 
    * @return true if time zone of formatter
    *  overridden for calendars
    */
   public boolean getTimeZoneOverridesCalendar() {
       return mTimeZoneForced;
   }
   /**
*

Gets the locale used by this formatter.

    * 
    * @return the locale
    */
   public Locale getLocale() {
       return mLocale;
   }
   /**
*

Gets an estimate for the maximum string length that the * formatter will produce.

    *
*

The actual formatted length will almost always be less than or * equal to this amount.

    * 
    * @return the maximum formatted length
    */
   public int getMaxLengthEstimate() {
       return mMaxLengthEstimate;
   }
   // Basics
   //-----------------------------------------------------------------------
   /**
*

Compares two objects for equality.

    * 
    * @param obj  the object to compare to
    * @return true if equal
    */
   public boolean equals(Object obj) {
       if (obj instanceof FastDateFormat == false) {
           return false;
       }
       FastDateFormat other = (FastDateFormat) obj;
       if (
           (mPattern == other.mPattern || mPattern.equals(other.mPattern)) &&
           (mTimeZone == other.mTimeZone || mTimeZone.equals(other.mTimeZone)) &&
           (mLocale == other.mLocale || mLocale.equals(other.mLocale)) &&
           (mTimeZoneForced == other.mTimeZoneForced) &&
           (mLocaleForced == other.mLocaleForced)
           ) {
           return true;
       }
       return false;
   }
   /**
*

Returns a hashcode compatible with equals.

    * 
    * @return a hashcode compatible with equals
    */
   public int hashCode() {
       int total = 0;
       total += mPattern.hashCode();
       total += mTimeZone.hashCode();
       total += (mTimeZoneForced ? 1 : 0);
       total += mLocale.hashCode();
       total += (mLocaleForced ? 1 : 0);
       return total;
   }
   /**
*

Gets a debugging string version of this formatter.

    * 
    * @return a debugging string
    */
   public String toString() {
       return "FastDateFormat[" + mPattern + "]";
   }
   // Serializing
   //-----------------------------------------------------------------------
   /**
    * Create the object after serialization. This implementation reinitializes the 
    * transient properties.
    *
    * @param in ObjectInputStream from which the object is being deserialized.
    * @throws IOException if there is an IO issue.
    * @throws ClassNotFoundException if a class cannot be found.
    */
   private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
       in.defaultReadObject();
       init();
   }
   
   // Rules
   //-----------------------------------------------------------------------
   /**
*

Inner class defining a rule.

    */
   private interface Rule {
       /**
        * Returns the estimated lentgh of the result.
        * 
        * @return the estimated length
        */
       int estimateLength();
       
       /**
        * Appends the value of the specified calendar to the output buffer based on the rule implementation.
        * 
        * @param buffer the output buffer
        * @param calendar calendar to be appended
        */
       void appendTo(StringBuffer buffer, Calendar calendar);
   }
   /**
*

Inner class defining a numeric rule.

    */
   private interface NumberRule extends Rule {
       /**
        * Appends the specified value to the output buffer based on the rule implementation.
        * 
        * @param buffer the output buffer
        * @param value the value to be appended
        */
       void appendTo(StringBuffer buffer, int value);
   }
   /**
*

Inner class to output a constant single character.

    */
   private static class CharacterLiteral implements Rule {
       private final char mValue;
       /**
        * Constructs a new instance of CharacterLiteral
        * to hold the specified value.
        * 
        * @param value the character literal
        */
       CharacterLiteral(char value) {
           mValue = value;
       }
       /**
        * {@inheritDoc}
        */
       public int estimateLength() {
           return 1;
       }
       /**
        * {@inheritDoc}
        */
       public void appendTo(StringBuffer buffer, Calendar calendar) {
           buffer.append(mValue);
       }
   }
   /**
*

Inner class to output a constant string.

    */
   private static class StringLiteral implements Rule {
       private final String mValue;
       /**
        * Constructs a new instance of StringLiteral
        * to hold the specified value.
        * 
        * @param value the string literal
        */
       StringLiteral(String value) {
           mValue = value;
       }
       /**
        * {@inheritDoc}
        */
       public int estimateLength() {
           return mValue.length();
       }
       /**
        * {@inheritDoc}
        */
       public void appendTo(StringBuffer buffer, Calendar calendar) {
           buffer.append(mValue);
       }
   }
   /**
*

Inner class to output one of a set of values.

    */
   private static class TextField implements Rule {
       private final int mField;
       private final String[] mValues;
       /**
        * Constructs an instance of TextField
        * with the specified field and values.
        * 
        * @param field the field
        * @param values the field values
        */
       TextField(int field, String[] values) {
           mField = field;
           mValues = values;
       }
       /**
        * {@inheritDoc}
        */
       public int estimateLength() {
           int max = 0;
           for (int i=mValues.length; --i >= 0; ) {
               int len = mValues[i].length();
               if (len > max) {
                   max = len;
               }
           }
           return max;
       }
       /**
        * {@inheritDoc}
        */
       public void appendTo(StringBuffer buffer, Calendar calendar) {
           buffer.append(mValues[calendar.get(mField)]);
       }
   }
   /**
*

Inner class to output an unpadded number.

    */
   private static class UnpaddedNumberField implements NumberRule {
       static final UnpaddedNumberField INSTANCE_YEAR = new UnpaddedNumberField(Calendar.YEAR);
       
       private final int mField;
       /**
        * Constructs an instance of UnpadedNumberField with the specified field.
        * 
        * @param field the field
        */
       UnpaddedNumberField(int field) {
           mField = field;
       }
       /**
        * {@inheritDoc}
        */
       public int estimateLength() {
           return 4;
       }
       /**
        * {@inheritDoc}
        */
       public void appendTo(StringBuffer buffer, Calendar calendar) {
           appendTo(buffer, calendar.get(mField));
       }
       /**
        * {@inheritDoc}
        */
       public final void appendTo(StringBuffer buffer, int value) {
           if (value < 10) {
               buffer.append((char)(value + "0"));
           } else if (value < 100) {
               buffer.append((char)(value / 10 + "0"));
               buffer.append((char)(value % 10 + "0"));
           } else {
               buffer.append(Integer.toString(value));
           }
       }
   }
   /**
*

Inner class to output an unpadded month.

    */
   private static class UnpaddedMonthField implements NumberRule {
       static final UnpaddedMonthField INSTANCE = new UnpaddedMonthField();
       /**
        * Constructs an instance of UnpaddedMonthField.
        *
        */
       UnpaddedMonthField() {
           super();
       }
       /**
        * {@inheritDoc}
        */
       public int estimateLength() {
           return 2;
       }
       /**
        * {@inheritDoc}
        */
       public void appendTo(StringBuffer buffer, Calendar calendar) {
           appendTo(buffer, calendar.get(Calendar.MONTH) + 1);
       }
       /**
        * {@inheritDoc}
        */
       public final void appendTo(StringBuffer buffer, int value) {
           if (value < 10) {
               buffer.append((char)(value + "0"));
           } else {
               buffer.append((char)(value / 10 + "0"));
               buffer.append((char)(value % 10 + "0"));
           }
       }
   }
   /**
*

Inner class to output a padded number.

    */
   private static class PaddedNumberField implements NumberRule {
       private final int mField;
       private final int mSize;
       /**
        * Constructs an instance of PaddedNumberField.
        * 
        * @param field the field
        * @param size size of the output field
        */
       PaddedNumberField(int field, int size) {
           if (size < 3) {
               // Should use UnpaddedNumberField or TwoDigitNumberField.
               throw new IllegalArgumentException();
           }
           mField = field;
           mSize = size;
       }
       /**
        * {@inheritDoc}
        */
       public int estimateLength() {
           return 4;
       }
       /**
        * {@inheritDoc}
        */
       public void appendTo(StringBuffer buffer, Calendar calendar) {
           appendTo(buffer, calendar.get(mField));
       }
       /**
        * {@inheritDoc}
        */
       public final void appendTo(StringBuffer buffer, int value) {
           if (value < 100) {
               for (int i = mSize; --i >= 2; ) {
                   buffer.append("0");
               }
               buffer.append((char)(value / 10 + "0"));
               buffer.append((char)(value % 10 + "0"));
           } else {
               int digits;
               if (value < 1000) {
                   digits = 3;
               } else {
                   digits = Integer.toString(value).length();
               }
               for (int i = mSize; --i >= digits; ) {
                   buffer.append("0");
               }
               buffer.append(Integer.toString(value));
           }
       }
   }
   /**
*

Inner class to output a two digit number.

    */
   private static class TwoDigitNumberField implements NumberRule {
       private final int mField;
       /**
        * Constructs an instance of TwoDigitNumberField with the specified field.
        * 
        * @param field the field
        */
       TwoDigitNumberField(int field) {
           mField = field;
       }
       /**
        * {@inheritDoc}
        */
       public int estimateLength() {
           return 2;
       }
       /**
        * {@inheritDoc}
        */
       public void appendTo(StringBuffer buffer, Calendar calendar) {
           appendTo(buffer, calendar.get(mField));
       }
       /**
        * {@inheritDoc}
        */
       public final void appendTo(StringBuffer buffer, int value) {
           if (value < 100) {
               buffer.append((char)(value / 10 + "0"));
               buffer.append((char)(value % 10 + "0"));
           } else {
               buffer.append(Integer.toString(value));
           }
       }
   }
   /**
*

Inner class to output a two digit year.

    */
   private static class TwoDigitYearField implements NumberRule {
       static final TwoDigitYearField INSTANCE = new TwoDigitYearField();
       /**
        * Constructs an instance of TwoDigitYearField.
        */
       TwoDigitYearField() {
           super();
       }
       /**
        * {@inheritDoc}
        */
       public int estimateLength() {
           return 2;
       }
       /**
        * {@inheritDoc}
        */
       public void appendTo(StringBuffer buffer, Calendar calendar) {
           appendTo(buffer, calendar.get(Calendar.YEAR) % 100);
       }
       /**
        * {@inheritDoc}
        */
       public final void appendTo(StringBuffer buffer, int value) {
           buffer.append((char)(value / 10 + "0"));
           buffer.append((char)(value % 10 + "0"));
       }
   }
   /**
*

Inner class to output a two digit month.

    */
   private static class TwoDigitMonthField implements NumberRule {
       static final TwoDigitMonthField INSTANCE = new TwoDigitMonthField();
       /**
        * Constructs an instance of TwoDigitMonthField.
        */
       TwoDigitMonthField() {
           super();
       }
       /**
        * {@inheritDoc}
        */
       public int estimateLength() {
           return 2;
       }
       /**
        * {@inheritDoc}
        */
       public void appendTo(StringBuffer buffer, Calendar calendar) {
           appendTo(buffer, calendar.get(Calendar.MONTH) + 1);
       }
       /**
        * {@inheritDoc}
        */
       public final void appendTo(StringBuffer buffer, int value) {
           buffer.append((char)(value / 10 + "0"));
           buffer.append((char)(value % 10 + "0"));
       }
   }
   /**
*

Inner class to output the twelve hour field.

    */
   private static class TwelveHourField implements NumberRule {
       private final NumberRule mRule;
       /**
        * Constructs an instance of TwelveHourField with the specified
        * NumberRule.
        * 
        * @param rule the rule
        */
       TwelveHourField(NumberRule rule) {
           mRule = rule;
       }
       /**
        * {@inheritDoc}
        */
       public int estimateLength() {
           return mRule.estimateLength();
       }
       /**
        * {@inheritDoc}
        */
       public void appendTo(StringBuffer buffer, Calendar calendar) {
           int value = calendar.get(Calendar.HOUR);
           if (value == 0) {
               value = calendar.getLeastMaximum(Calendar.HOUR) + 1;
           }
           mRule.appendTo(buffer, value);
       }
       /**
        * {@inheritDoc}
        */
       public void appendTo(StringBuffer buffer, int value) {
           mRule.appendTo(buffer, value);
       }
   }
   /**
*

Inner class to output the twenty four hour field.

    */
   private static class TwentyFourHourField implements NumberRule {
       private final NumberRule mRule;
       /**
        * Constructs an instance of TwentyFourHourField with the specified
        * NumberRule.
        * 
        * @param rule the rule
        */
       TwentyFourHourField(NumberRule rule) {
           mRule = rule;
       }
       /**
        * {@inheritDoc}
        */
       public int estimateLength() {
           return mRule.estimateLength();
       }
       /**
        * {@inheritDoc}
        */
       public void appendTo(StringBuffer buffer, Calendar calendar) {
           int value = calendar.get(Calendar.HOUR_OF_DAY);
           if (value == 0) {
               value = calendar.getMaximum(Calendar.HOUR_OF_DAY) + 1;
           }
           mRule.appendTo(buffer, value);
       }
       /**
        * {@inheritDoc}
        */
       public void appendTo(StringBuffer buffer, int value) {
           mRule.appendTo(buffer, value);
       }
   }
   /**
*

Inner class to output a time zone name.

    */
   private static class TimeZoneNameRule implements Rule {
       private final TimeZone mTimeZone;
       private final boolean mTimeZoneForced;
       private final Locale mLocale;
       private final int mStyle;
       private final String mStandard;
       private final String mDaylight;
       /**
        * Constructs an instance of TimeZoneNameRule with the specified properties.
        * 
        * @param timeZone the time zone
        * @param timeZoneForced if true the time zone is forced into standard and daylight
        * @param locale the locale
        * @param style the style
        */
       TimeZoneNameRule(TimeZone timeZone, boolean timeZoneForced, Locale locale, int style) {
           mTimeZone = timeZone;
           mTimeZoneForced = timeZoneForced;
           mLocale = locale;
           mStyle = style;
           if (timeZoneForced) {
               mStandard = getTimeZoneDisplay(timeZone, false, style, locale);
               mDaylight = getTimeZoneDisplay(timeZone, true, style, locale);
           } else {
               mStandard = null;
               mDaylight = null;
           }
       }
       /**
        * {@inheritDoc}
        */
       public int estimateLength() {
           if (mTimeZoneForced) {
               return Math.max(mStandard.length(), mDaylight.length());
           } else if (mStyle == TimeZone.SHORT) {
               return 4;
           } else {
               return 40;
           }
       }
       /**
        * {@inheritDoc}
        */
       public void appendTo(StringBuffer buffer, Calendar calendar) {
           if (mTimeZoneForced) {
               if (mTimeZone.useDaylightTime() && calendar.get(Calendar.DST_OFFSET) != 0) {
                   buffer.append(mDaylight);
               } else {
                   buffer.append(mStandard);
               }
           } else {
               TimeZone timeZone = calendar.getTimeZone();
               if (timeZone.useDaylightTime() && calendar.get(Calendar.DST_OFFSET) != 0) {
                   buffer.append(getTimeZoneDisplay(timeZone, true, mStyle, mLocale));
               } else {
                   buffer.append(getTimeZoneDisplay(timeZone, false, mStyle, mLocale));
               }
           }
       }
   }
   /**
*

Inner class to output a time zone as a number +/-HHMM * or +/-HH:MM.

    */
   private static class TimeZoneNumberRule implements Rule {
       static final TimeZoneNumberRule INSTANCE_COLON = new TimeZoneNumberRule(true);
       static final TimeZoneNumberRule INSTANCE_NO_COLON = new TimeZoneNumberRule(false);
       
       final boolean mColon;
       
       /**
        * Constructs an instance of TimeZoneNumberRule with the specified properties.
        * 
        * @param colon add colon between HH and MM in the output if true
        */
       TimeZoneNumberRule(boolean colon) {
           mColon = colon;
       }
       /**
        * {@inheritDoc}
        */
       public int estimateLength() {
           return 5;
       }
       /**
        * {@inheritDoc}
        */
       public void appendTo(StringBuffer buffer, Calendar calendar) {
           int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
           
           if (offset < 0) {
               buffer.append("-");
               offset = -offset;
           } else {
               buffer.append("+");
           }
           
           int hours = offset / (60 * 60 * 1000);
           buffer.append((char)(hours / 10 + "0"));
           buffer.append((char)(hours % 10 + "0"));
           
           if (mColon) {
               buffer.append(":");
           }
           
           int minutes = offset / (60 * 1000) - 60 * hours;
           buffer.append((char)(minutes / 10 + "0"));
           buffer.append((char)(minutes % 10 + "0"));
       }            
   }
   // ----------------------------------------------------------------------
   /**
*

Inner class that acts as a compound key for time zone names.

    */
   private static class TimeZoneDisplayKey {
       private final TimeZone mTimeZone;
       private final int mStyle;
       private final Locale mLocale;
       /**
        * Constructs an instance of TimeZoneDisplayKey with the specified properties.
        *  
        * @param timeZone the time zone
        * @param daylight adjust the style for daylight saving time if true
        * @param style the timezone style
        * @param locale the timezone locale
        */
       TimeZoneDisplayKey(TimeZone timeZone,
                          boolean daylight, int style, Locale locale) {
           mTimeZone = timeZone;
           if (daylight) {
               style |= 0x80000000;
           }
           mStyle = style;
           mLocale = locale;
       }
       /**
        * {@inheritDoc}
        */
       public int hashCode() {
           return mStyle * 31 + mLocale.hashCode();
       }
       /**
        * {@inheritDoc}
        */
       public boolean equals(Object obj) {
           if (this == obj) {
               return true;
           }
           if (obj instanceof TimeZoneDisplayKey) {
               TimeZoneDisplayKey other = (TimeZoneDisplayKey)obj;
               return
                   mTimeZone.equals(other.mTimeZone) &&
                   mStyle == other.mStyle &&
                   mLocale.equals(other.mLocale);
           }
           return false;
       }
   }
   // ----------------------------------------------------------------------
   /**
*

Helper class for creating compound objects.

    *
*

One use for this class is to create a hashtable key * out of multiple objects.

    */
   private static class Pair {
       private final Object mObj1;
       private final Object mObj2;
       /**
        * Constructs an instance of Pair to hold the specified objects.
        * @param obj1 one object in the pair
        * @param obj2 second object in the pair
        */
       public Pair(Object obj1, Object obj2) {
           mObj1 = obj1;
           mObj2 = obj2;
       }
       /**
        * {@inheritDoc}
        */
       public boolean equals(Object obj) {
           if (this == obj) {
               return true;
           }
           if (!(obj instanceof Pair)) {
               return false;
           }
           Pair key = (Pair)obj;
           return
               (mObj1 == null ?
                key.mObj1 == null : mObj1.equals(key.mObj1)) &&
               (mObj2 == null ?
                key.mObj2 == null : mObj2.equals(key.mObj2));
       }
       /**
        * {@inheritDoc}
        */
       public int hashCode() {
           return
               (mObj1 == null ? 0 : mObj1.hashCode()) +
               (mObj2 == null ? 0 : mObj2.hashCode());
       }
       /**
        * {@inheritDoc}
        */
       public String toString() {
           return "[" + mObj1 + ":" + mObj2 + "]";
       }
   }

}


 </source>
   
  
 
  



Date and time with day and month fully spelled-out

   <source lang="java">
   

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));
 }

}



 </source>
   
  
 
  



Date and time with month

   <source lang="java">
   

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));
 }

}



 </source>
   
  
 
  



DateCalAdd -- compute the difference between two dates

   <source lang="java">
    

import java.text.SimpleDateFormat; import java.util.Calendar; /**

* DateCalAdd -- compute the difference between two dates.
*/

public class DateCalAdd {

 public static void main(String[] av) {
   /** Today"s date */
   Calendar now = Calendar.getInstance();
   /* Do "DateFormat" using "simple" format. */
   SimpleDateFormat formatter = new SimpleDateFormat(
       "E yyyy/MM/dd "at" hh:mm:ss a zzz");
   System.out.println("It is now " + formatter.format(now.getTime()));
   now.add(Calendar.YEAR, -2);
   System.out.println("Two years ago was "
       + formatter.format(now.getTime()));
 }

}




 </source>
   
  
 
  



DateDiff -- compute the difference between two dates

   <source lang="java">
    

import java.util.Date; import java.util.GregorianCalendar; /**

* DateDiff -- compute the difference between two dates.
*/

public class DateDiff {

 public static void main(String[] av) {
   /** The date at the end of the last century */
   Date d1 = new GregorianCalendar(2000, 11, 31, 23, 59).getTime();
   /** Today"s date */
   Date today = new Date();
   // Get msec from each, and subtract.
   long diff = today.getTime() - d1.getTime();
   System.out.println("The 21st century (up to " + today + ") is "
       + (diff / (1000 * 60 * 60 * 24)) + " days old.");
 }

}




 </source>
   
  
 
  



Date Format Cache.

   <source lang="java">
  

// // Copyright 2004-2005 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // Licensed 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.text.DateFormatSymbols; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /* ------------------------------------------------------------ */ /**

* Date Format Cache. Computes String representations of Dates and caches the
* results so that subsequent requests within the same minute will be fast.
* 
* Only format strings that contain either "ss" or "ss.SSS" are handled.
* 
* The timezone of the date may be included as an ID with the "zzz" format
* string or as an offset with the "ZZZ" format string.
* 
* If consecutive calls are frequently very different, then this may be a little
* slower than a normal DateFormat.
* 
* @author Kent Johnson <KJohnson@transparent.ru>
* @author Greg Wilkins (gregw)
*/

public class DateCache {

 private static long __hitWindow = 60 * 60;
 private static long __MaxMisses = 10;
 private String _formatString;
 private String _tzFormatString;
 private SimpleDateFormat _tzFormat;
 private String _minFormatString;
 private SimpleDateFormat _minFormat;
 private String _secFormatString;
 private String _secFormatString0;
 private String _secFormatString1;
 private boolean _millis = false;
 private long _misses = 0;
 private long _lastMinutes = -1;
 private long _lastSeconds = -1;
 private String _lastResult = null;
 private Locale _locale = null;
 private DateFormatSymbols _dfs = null;
 /* ------------------------------------------------------------ */
 /**
  * Constructor. Make a DateCache that will use a default format. The default
  * format generates the same results as Date.toString().
  */
 public DateCache() {
   this("EEE MMM dd HH:mm:ss zzz yyyy");
   getFormat().setTimeZone(TimeZone.getDefault());
 }
 /* ------------------------------------------------------------ */
 /**
  * Constructor. Make a DateCache that will use the given format
  */
 public DateCache(String format) {
   _formatString = format;
   setTimeZone(TimeZone.getDefault());
 }
 /* ------------------------------------------------------------ */
 public DateCache(String format, Locale l) {
   _formatString = format;
   _locale = l;
   setTimeZone(TimeZone.getDefault());
 }
 /* ------------------------------------------------------------ */
 public DateCache(String format, DateFormatSymbols s) {
   _formatString = format;
   _dfs = s;
   setTimeZone(TimeZone.getDefault());
 }
 /* ------------------------------------------------------------ */
 /**
  * Set the timezone.
  * 
  * @param tz
  *          TimeZone
  */
 public void setTimeZone(TimeZone tz) {
   setTzFormatString(tz);
   if (_locale != null) {
     _tzFormat = new SimpleDateFormat(_tzFormatString, _locale);
     _minFormat = new SimpleDateFormat(_minFormatString, _locale);
   } else if (_dfs != null) {
     _tzFormat = new SimpleDateFormat(_tzFormatString, _dfs);
     _minFormat = new SimpleDateFormat(_minFormatString, _dfs);
   } else {
     _tzFormat = new SimpleDateFormat(_tzFormatString);
     _minFormat = new SimpleDateFormat(_minFormatString);
   }
   _tzFormat.setTimeZone(tz);
   _minFormat.setTimeZone(tz);
   _lastSeconds = -1;
   _lastMinutes = -1;
 }
 /* ------------------------------------------------------------ */
 public TimeZone getTimeZone() {
   return _tzFormat.getTimeZone();
 }
 /* ------------------------------------------------------------ */
 /**
  * Set the timezone.
  * 
  * @param timeZoneId
  *          TimeZoneId the ID of the zone as used by TimeZone.getTimeZone(id)
  */
 public void setTimeZoneID(String timeZoneId) {
   setTimeZone(TimeZone.getTimeZone(timeZoneId));
 }
 /* ------------------------------------------------------------ */
 private void setTzFormatString(final TimeZone tz) {
   int zIndex = _formatString.indexOf("ZZZ");
   if (zIndex >= 0) {
     String ss1 = _formatString.substring(0, zIndex);
     String ss2 = _formatString.substring(zIndex + 3);
     int tzOffset = tz.getRawOffset();
     StringBuffer sb = new StringBuffer(_formatString.length() + 10);
     sb.append(ss1);
     sb.append(""");
     if (tzOffset >= 0)
       sb.append("+");
     else {
       tzOffset = -tzOffset;
       sb.append("-");
     }
     int raw = tzOffset / (1000 * 60); // Convert to seconds
     int hr = raw / 60;
     int min = raw % 60;
     if (hr < 10)
       sb.append("0");
     sb.append(hr);
     if (min < 10)
       sb.append("0");
     sb.append(min);
     sb.append("\"");
     sb.append(ss2);
     _tzFormatString = sb.toString();
   } else
     _tzFormatString = _formatString;
   setMinFormatString();
 }
 /* ------------------------------------------------------------ */
 private void setMinFormatString() {
   int i = _tzFormatString.indexOf("ss.SSS");
   int l = 6;
   if (i >= 0)
     _millis = true;
   else {
     i = _tzFormatString.indexOf("ss");
     l = 2;
   }
   // Build a formatter that formats a second format string
   // Have to replace @ with " later due to bug in SimpleDateFormat
   String ss1 = _tzFormatString.substring(0, i);
   String ss2 = _tzFormatString.substring(i + l);
   _minFormatString = ss1 + (_millis ? ""ss.SSS"" : ""ss"") + ss2;
 }
 /* ------------------------------------------------------------ */
 /**
  * Format a date according to our stored formatter.
  * 
  * @param inDate
  * @return Formatted date
  */
 public synchronized String format(Date inDate) {
   return format(inDate.getTime());
 }
 /* ------------------------------------------------------------ */
 /**
  * Format a date according to our stored formatter.
  * 
  * @param inDate
  * @return Formatted date
  */
 public synchronized String format(long inDate) {
   long seconds = inDate / 1000;
   // Is it not suitable to cache?
   if (seconds < _lastSeconds || _lastSeconds > 0 && seconds > _lastSeconds + __hitWindow) {
     // It"s a cache miss
     _misses++;
     if (_misses < __MaxMisses) {
       Date d = new Date(inDate);
       return _tzFormat.format(d);
     }
   } else if (_misses > 0)
     _misses--;
   // Check if we are in the same second
   // and don"t care about millis
   if (_lastSeconds == seconds && !_millis)
     return _lastResult;
   Date d = new Date(inDate);
   // Check if we need a new format string
   long minutes = seconds / 60;
   if (_lastMinutes != minutes) {
     _lastMinutes = minutes;
     _secFormatString = _minFormat.format(d);
     int i;
     int l;
     if (_millis) {
       i = _secFormatString.indexOf("ss.SSS");
       l = 6;
     } else {
       i = _secFormatString.indexOf("ss");
       l = 2;
     }
     _secFormatString0 = _secFormatString.substring(0, i);
     _secFormatString1 = _secFormatString.substring(i + l);
   }
   // Always format if we get here
   _lastSeconds = seconds;
   StringBuffer sb = new StringBuffer(_secFormatString.length());
   synchronized (sb) {
     sb.append(_secFormatString0);
     int s = (int) (seconds % 60);
     if (s < 10)
       sb.append("0");
     sb.append(s);
     if (_millis) {
       long millis = inDate % 1000;
       if (millis < 10)
         sb.append(".00");
       else if (millis < 100)
         sb.append(".0");
       else
         sb.append(".");
       sb.append(millis);
     }
     sb.append(_secFormatString1);
     _lastResult = sb.toString();
   }
   return _lastResult;
 }
 /* ------------------------------------------------------------ */
 /**
  * Format to string buffer.
  * 
  * @param inDate
  *          Date the format
  * @param buffer
  *          StringBuffer
  */
 public void format(long inDate, StringBuffer buffer) {
   buffer.append(format(inDate));
 }
 /* ------------------------------------------------------------ */
 /**
  * Get the format.
  */
 public SimpleDateFormat getFormat() {
   return _minFormat;
 }
 /* ------------------------------------------------------------ */
 public String getFormatString() {
   return _formatString;
 }
 /* ------------------------------------------------------------ */
 public String now() {
   return format(System.currentTimeMillis());
 }

}


 </source>
   
  
 
  



Determine if an hour is between an interval

   <source lang="java">
    

import java.text.SimpleDateFormat;

public class Main{

   static String  HOUR_FORMAT = "HH:mm";
   static SimpleDateFormat sdfHour = new SimpleDateFormat(HOUR_FORMAT);
   public static boolean isHourInInterval(String target, String start, String end) {
       return ((target.rupareTo(start) >= 0)&& (target.rupareTo(end) <= 0));
   }
   public static void main (String[] args) {
     String now = "12";
     String start = "14:00";
     String end   = "14:26";
     System. out.println(now + " between " + start + "-" + end + "?");
     System. out.println(isHourInInterval(now,start,end));
   }
  

}



 </source>
   
  
 
  



Determine the day of the week

   <source lang="java">
    

import java.util.Calendar; import java.util.GregorianCalendar; public class Main {

 public static void main(String[] argv) throws Exception {
   GregorianCalendar newCal = new GregorianCalendar();
   int day = newCal.get(Calendar.DAY_OF_WEEK);
   newCal = new GregorianCalendar();
   newCal.set(1997, 2, 1, 0, 0, 0);
   newCal.setTime(newCal.getTime());
   day = newCal.get(Calendar.DAY_OF_WEEK);
 }

}



 </source>
   
  
 
  



Determining If a Year Is a Leap Year

   <source lang="java">
    

import java.util.GregorianCalendar; public class Main {

 public static void main(String[] argv) throws Exception {
   GregorianCalendar cal = new GregorianCalendar();
   boolean b = cal.isLeapYear(1998); // false
   b = cal.isLeapYear(2000); // true
   b = cal.isLeapYear(0); // true
 }

}



 </source>
   
  
 
  



Determining the Day-of-Week for a Particular Date

   <source lang="java">
    

import java.util.Calendar; import java.util.GregorianCalendar; public class Main {

 public static void main(String[] argv) throws Exception {
   Calendar xmas = new GregorianCalendar(1998, Calendar.DECEMBER, 25);
   int dayOfWeek = xmas.get(Calendar.DAY_OF_WEEK); // 6=Friday
   Calendar cal = new GregorianCalendar(2003, Calendar.JANUARY, 1);
   dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); // 4=Wednesday
 }

}



 </source>
   
  
 
  



Display date with a short day and month name

   <source lang="java">
   

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);
 }

}



 </source>
   
  
 
  



Display Day of Week using Java Calendar

   <source lang="java">
    

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   Calendar now = Calendar.getInstance();
   System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1) + "-"
       + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
   String[] strDays = new String[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thusday",
       "Friday", "Saturday" };
   // Day_OF_WEEK starts from 1 while array index starts from 0
   System.out.println("Current day is : " + strDays[now.get(Calendar.DAY_OF_WEEK) - 1]);
 }

}




 </source>
   
  
 
  



Display full date time

   <source lang="java">
    

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   Calendar now = Calendar.getInstance();
   System.out.println("Current full date time is : " + (now.get(Calendar.MONTH) + 1) + "-"
       + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR) + " "
       + now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE) + ":"
       + now.get(Calendar.SECOND) + "." + now.get(Calendar.MILLISECOND));
 }

}



 </source>
   
  
 
  



Display Month of year using Java Calendar

   <source lang="java">
    

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   Calendar now = Calendar.getInstance();
   System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1) + "-"
       + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
   String[] strMonths = new String[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
       "Sep", "Oct", "Nov", "Dec" };
   System.out.println("Current month is : " + strMonths[now.get(Calendar.MONTH)]);
 }

}



 </source>
   
  
 
  



Easter - compute the day on which Easter falls

   <source lang="java">
    

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

import java.util.Calendar; import java.util.GregorianCalendar; /**

* Easter - compute the day on which Easter falls.
* 
* In the Christian religion, Easter is possibly the most important holiday of
* the year, so getting its date just so  is worthwhile.
* 
* @author: Ian F. Darwin, http://www.darwinsys.ru/, based on a detailed
*          algorithm in Knuth, vol 1, pg 155.
* 
* @Version: $Id: Easter.java,v 1.5 2004/02/09 03:33:46 ian Exp $ Written in C,
*           Toronto, 1988. Java version 1996.
* 
* @Note: It"s not proven correct, although it gets the right answer for years
*        around the present.
*/

public class Easter {

 /*
  * Compute the day of the year that Easter falls on. Step names E1 E2 etc.,
  * are direct references to Knuth, Vol 1, p 155. @exception
  * IllegalArgumentexception If the year is before 1582 (since the algorithm
  * only works on the Gregorian calendar).
  */
 public static final Calendar findHolyDay(int year) {
   if (year <= 1582) {
     throw new IllegalArgumentException(
         "Algorithm invalid before April 1583");
   }
   int golden, century, x, z, d, epact, n;
   golden = (year % 19) + 1; /* E1: metonic cycle */
   century = (year / 100) + 1; /* E2: e.g. 1984 was in 20th C */
   x = (3 * century / 4) - 12; /* E3: leap year correction */
   z = ((8 * century + 5) / 25) - 5; /* E3: sync with moon"s orbit */
   d = (5 * year / 4) - x - 10;
   epact = (11 * golden + 20 + z - x) % 30; /* E5: epact */
   if ((epact == 25 && golden > 11) || epact == 24)
     epact++;
   n = 44 - epact;
   n += 30 * (n < 21 ? 1 : 0); /* E6: */
   n += 7 - ((d + n) % 7);
   if (n > 31) /* E7: */
     return new GregorianCalendar(year, 4 - 1, n - 31); /* April */
   else
     return new GregorianCalendar(year, 3 - 1, n); /* March */
 }
 /** Main program, when used as a standalone application */
 public static void main(String[] argv) {
   if (argv.length == 0) {
     int thisYear = new GregorianCalendar().get(Calendar.YEAR);
     Calendar c = Easter.findHolyDay(thisYear);
     System.out.println(c.getTime());
   } else
     for (int i = 0; i < argv.length; i++) {
       int year = 0;
       try {
         year = Integer.parseInt(argv[i]);
         System.out.println(Easter.findHolyDay(year).getTime());
       } catch (IllegalArgumentException e) {
         System.err.println("Year " + argv[i] + " invalid ("
             + e.getMessage() + ").");
       }
     }
 }

}




 </source>
   
  
 
  



Express a duration in term of HH:MM:SS

   <source lang="java">
    

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);
 }

}



 </source>
   
  
 
  



Format a duration in ms into a string as "Days,Hours,minutes and seconds"

   <source lang="java">
    

public class Main {

 public final static long ONE_SECOND = 1000;
 public final static long ONE_MINUTE = ONE_SECOND * 60;
 public final static long ONE_HOUR = ONE_MINUTE * 60;
 public final static long ONE_DAY = ONE_HOUR * 24;
 public static void millisecondToDHMS(long duration) {
   long temp = 0;
   if (duration >= ONE_SECOND) {
     temp = duration / ONE_DAY;
     if (temp > 0) {
       System.out.print(temp + " day");
       if (temp > 1) {
         System.out.print("s");
       }
     }
     temp = duration / ONE_HOUR;
     if (temp > 0) {
       System.out.print(temp + " hour");
       if (temp > 1) {
         System.out.print("s");
       }
     }
     temp = duration / ONE_MINUTE;
     if (temp > 0) {
       System.out.print( temp + " minute");
       if (temp > 1) {
         System.out.print("s");
       }
     }
     temp = duration / ONE_SECOND;
     if (temp > 0) {
       System.out.print(" second");
       if (temp > 1) {
         System.out.print("s");
       }
     }
   } 
 }
 public static void main(String args[]) {
   millisecondToDHMS(System.currentTimeMillis());
 }

}



 </source>
   
  
 
  



Formatter that caches formatted date information

   <source lang="java">
  

/*

* 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));
       }
   }

}


 </source>
   
  
 
  



Formatting dates into Strings.

   <source lang="java">
  

/*

  Derby - Class org.apache.derby.iapi.util.CheapDateFormatter
  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.
*/

/**

* This class contains static methods for formatting dates into Strings.
* It can be used where standard Date formatting is judged to be too
* expensive.
*/

public class CheapDateFormatter {

 static final long SECONDS  = 1000L;
 static final long MINUTES = SECONDS * 60L;
 static final long HOURS = MINUTES * 60L;
 static final long DAYS = HOURS * 24L;
 static final long NORMAL_YEAR = DAYS * 365L;
 static final long LEAP_YEAR = NORMAL_YEAR + DAYS;
 static final long FOURYEARS = (NORMAL_YEAR * 3L) + LEAP_YEAR;
 static final long END_OF_FIRST_YEAR = NORMAL_YEAR;
 static final long END_OF_SECOND_YEAR = END_OF_FIRST_YEAR + LEAP_YEAR;
 static final long END_OF_THIRD_YEAR = END_OF_SECOND_YEAR + NORMAL_YEAR;
 static final int[] DAYS_IN_MONTH = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
 static final int FEBRUARY = 1;
 /**
  * This method formats the current date into a String. The input is
  * a long representing the number of milliseconds since Jan. 1, 1970.
  * The output is a String in the form yyyy/mm/dd hh:mm:ss.ddd GMT.
  *
  * The purpose of this class is to format date strings without paying
  * the price of instantiating ResourceBundles and Locales, which the
  * java.util.Date class does whenever you format a date string.
  * As a result, the output of this class is not localized, it does
  * not take the local time zone into account, and it is possible that
  * it will not be as accurate as the standard Date class. It is OK
  * to use this method when, for example, formatting timestamps to
  * write to db2j.LOG, but not for manipulating dates in language
  * processing.
  *
  * @param time  The current time in milliseconds since Jan. 1, 1970
  *
  * @return The date formatted as yyyy/mm/dd hh:mm:ss.ddd GMT.
  */
 public static String formatDate(long time) {
   // Assume not a leap year until we know otherwise
   boolean leapYear = false;
   // How many four year periods since Jan. 1, 1970?
   long year = ((time / FOURYEARS) * 4L);
   // How much time is left over after the four-year periods?
   long leftover = time % FOURYEARS;
   time -= (year / 4L) * FOURYEARS;
   year += 1970L;
   // Does time extend past end of first year in four-year period?
   if (leftover >= END_OF_FIRST_YEAR) {
     year++;
     time -= NORMAL_YEAR;
   }
   // Does time extend past end of second year in four-year period?
   if (leftover >= END_OF_SECOND_YEAR) {
     year++;
     time -= NORMAL_YEAR;
   }
   // Does time extend past end of third year in four-year period?
   if (leftover >= END_OF_THIRD_YEAR) {
     year++;
     time -= LEAP_YEAR;
   }
   // It"s a leap year if divisible by 4, unless divisible by 100,
   // unless divisible by 400.
   if ((year % 4L) == 0) {
     if ((year % 100L) == 0) {
       if ((year % 400L) == 0) {
         leapYear = true;
       }
     }
     leapYear = true;
   }
   // What day of the year is this, starting at 1?
   long days = (time / DAYS) + 1;
   // What month is this, starting at 1?
   int month = 1;
   for (int i = 0; i < DAYS_IN_MONTH.length; i++) {
     int daysInMonth;
     if (leapYear && (i == FEBRUARY)) {
       // February has 29 days in a leap year
       daysInMonth = 29;
     } else {
       // Get number of days in next month
       daysInMonth = DAYS_IN_MONTH[i];
     }
     // Is date after the month we are looking at?
     if (days > daysInMonth) {
       // Count number of months
       month++;
       // Subtract number of days in month
       days -= daysInMonth;
     } else {
       // Don"t bother to look any more - the date is within
       // the current month.
       break;
     }
   }
   // How much time is left after days are accounted for?
   time %= DAYS;
   long hours = time / HOURS;
   // How much time is left after hours are accounted for?
   time %= HOURS;
   long minutes = time / MINUTES;
   // How much time is left after minutes are accounted for?
   time %= MINUTES;
   long seconds = time / SECONDS;
   // How much time is left after seconds are accounted for?
   time %= SECONDS;
   return year + "-" +
       twoDigits(month) + "-" +
       twoDigits(days) + " " +
       twoDigits(hours) + ":" +
       twoDigits(minutes) + ":" +
       twoDigits(seconds) + "." +
       threeDigits(time) + " GMT";
 }
 private static String twoDigits(long val) {
   String retval;
   if (val < 10) {
     retval = "0" + val;
   } else {
     retval = Long.toString(val);
   }
   return retval;
 }
 private static String threeDigits(long val) {
   String retval;
   if (val < 10) {
     retval = "00" + val;
   } else if (val < 100) {
     retval = "0" + val;
   } else {
     retval = Long.toString(val);
   }
   return retval;
 }

}


 </source>
   
  
 
  



Formatting date with full day and month name and show time up to milliseconds with AM/PM

   <source lang="java">
   

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("EEEE, dd MMMM yyyy, hh:mm:ss.SSS a");
   String today = formatter.format(new Date());
   System.out.println("Today : " + today);
 }

}



 </source>
   
  
 
  



Formatting Symbols for SimpleDateFormat

   <source lang="java">
   

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



 </source>
   
  
 
  



Formatting the Time Using a Custom Format

   <source lang="java">
   

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);
 }

}



 </source>
   
  
 
  



Get a List of Month Names

   <source lang="java">
    

import java.text.DateFormatSymbols; public class Main {

 public static void main(String[] args) {
   String[] months = new DateFormatSymbols().getMonths();
   for (int i = 0; i < months.length; i++) {
     String month = months[i];
     System.out.println("month = " + month);
   }
 }

}



 </source>
   
  
 
  



Get current date, year and month

   <source lang="java">
    

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   Calendar now = Calendar.getInstance();
   // 
   System.out.println("Current Year is : " + now.get(Calendar.YEAR));
   // month start from 0 to 11
   System.out.println("Current Month is : " + (now.get(Calendar.MONTH) + 1));
   System.out.println("Current Date is : " + now.get(Calendar.DATE));
 }

}




 </source>
   
  
 
  



Get day, month, year value from the current date

   <source lang="java">
    

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   Calendar cal = Calendar.getInstance();
   int day = cal.get(Calendar.DATE);
   int month = cal.get(Calendar.MONTH) + 1;
   int year = cal.get(Calendar.YEAR);
   int dow = cal.get(Calendar.DAY_OF_WEEK);
   int dom = cal.get(Calendar.DAY_OF_MONTH);
   int doy = cal.get(Calendar.DAY_OF_YEAR);
   System.out.println("Current Date: " + cal.getTime());
   System.out.println("Day: " + day);
   System.out.println("Month: " + month);
   System.out.println("Year: " + year);
   System.out.println("Day of Week: " + dow);
   System.out.println("Day of Month: " + dom);
   System.out.println("Day of Year: " + doy);
 }

}



 </source>
   
  
 
  



Get day of week

   <source lang="java">
    

import java.util.Calendar;

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   Calendar calendar = Calendar.getInstance();
   calendar.set(Calendar.YEAR, 2007);
   calendar.set(Calendar.DAY_OF_YEAR, 180);
   // See the full information of the calendar object.
   System.out.println(calendar.getTime().toString());
   // Get the weekday and print it
   int weekday = calendar.get(Calendar.DAY_OF_WEEK);
   System.out.println("Weekday: " + weekday);
 }

}



 </source>
   
  
 
  



Get the current month name

   <source lang="java">
    

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   String[] monthName = { "January", "February", "March", "April", "May", "June", "July",
       "August", "September", "October", "November", "December" };
   Calendar cal = Calendar.getInstance();
   String month = monthName[cal.get(Calendar.MONTH)];
   System.out.println("Month name: " + month);
 }

}



 </source>
   
  
 
  



Get the day name

   <source lang="java">
   

import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class Main{

 public static void main(String[] args) {
   Date date1 = (new GregorianCalendar(2009, Calendar.OCTOBER, 17)).getTime();
   System.out.println(new SimpleDateFormat("EEEE").format(date1));
 }

}



 </source>
   
  
 
  



Get the last date of a month

   <source lang="java">
    

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   Calendar calendar = Calendar.getInstance();
   int lastDate = calendar.getActualMaximum(Calendar.DATE);
   System.out.println("Date     : " + calendar.getTime());
   System.out.println("Last Date: " + lastDate);
 }

}



 </source>
   
  
 
  



Get the number of days in that month

   <source lang="java">
    

import java.util.Calendar; public class Main {

 public static void main(String[] argv) throws Exception {
   Calendar cal = Calendar.getInstance();
   int days = cal.getActualMaximum(Calendar.DAY_OF_MONTH); // 28
 }

}



 </source>
   
  
 
  



Getting the Current Time

   <source lang="java">
    

import java.util.Calendar; import java.util.GregorianCalendar; public class Main {

 public static void main(String[] argv) throws Exception {
   Calendar cal = new GregorianCalendar();
   // Get the components of the time
   int hour12 = cal.get(Calendar.HOUR); // 0..11
   int hour24 = cal.get(Calendar.HOUR_OF_DAY); // 0..23
   int min = cal.get(Calendar.MINUTE); // 0..59
   int sec = cal.get(Calendar.SECOND); // 0..59
   int ms = cal.get(Calendar.MILLISECOND); // 0..999
   int ampm = cal.get(Calendar.AM_PM); // 0=AM, 1=PM
 }

}



 </source>
   
  
 
  



Get Week of month and year using Java Calendar

   <source lang="java">
    

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   Calendar now = Calendar.getInstance();
   System.out.println("Current week of month is : " + now.get(Calendar.WEEK_OF_MONTH));
   System.out.println("Current week of year is : " + now.get(Calendar.WEEK_OF_YEAR));
   now.add(Calendar.WEEK_OF_MONTH, 1);
   System.out.println("date after one year : " + (now.get(Calendar.MONTH) + 1) + "-"
       + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
 }

}



 </source>
   
  
 
  



How quickly can you press return

   <source lang="java">
    

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

import java.io.IOException; import java.text.DecimalFormat; /**

* How quickly can you press return?
* 
* @author Ian Darwin, http://www.darwinsys.ru/
* @version $Id: Timer0.java,v 1.4 2004/02/09 03:33:46 ian Exp $
*/

public class Timer0 {

 public static void main(String[] argv) throws IOException {
   //+
   long t0, t1;
   System.out.println("Press return when ready");
   t0 = System.currentTimeMillis();
   int b;
   do {
     b = System.in.read();
   } while (b != "\r" && b != "\n");
   t1 = System.currentTimeMillis();
   double deltaT = t1 - t0;
   System.out.println("You took "
       + DecimalFormat.getInstance().format(deltaT / 1000.)
       + " seconds.");
   //-
 }

}




 </source>
   
  
 
  



If a date is after another date

   <source lang="java">
    

import java.util.Calendar; import java.util.Date; public class Main {

 public static void main(String[] args) {
   Date today = new Date();
   Calendar calendar = Calendar.getInstance();
   calendar.add(Calendar.DATE, 1);
   Date tomorrow = calendar.getTime();
   if (tomorrow.after(today)) {
     System.out.println(tomorrow + " is after " + today);
   }
 }

}



 </source>
   
  
 
  



If a date is before another date

   <source lang="java">
    

import java.util.Calendar; import java.util.Date; public class Main {

 public static void main(String[] args) {
   Date today = new Date();
   Calendar calendar = Calendar.getInstance();
   calendar.add(Calendar.DATE, -1);
   Date yesterday = calendar.getTime();
   if (yesterday.before(today)) {
     System.out.println(yesterday + " is before " + today);
   }
 }

}



 </source>
   
  
 
  



Increment and Decrement a Date Using the Calendar Class

   <source lang="java">
    

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   Calendar cal = Calendar.getInstance();
   System.out.println("Now : " + cal.getTime());
   int daysToIncrement = 5;
   cal.add(Calendar.DATE, daysToIncrement);
   System.out.println("Date after increment: " + cal.getTime());
 }

}



 </source>
   
  
 
  



Increment and Decrement Months Using the Calendar Class

   <source lang="java">
    

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   Calendar cal = Calendar.getInstance();
   System.out.println("Now : " + cal.getTime());
   int monthsToDecrement = -1;
   cal.add(Calendar.MONTH, monthsToDecrement);
   System.out.println("Date after decrement: " + cal.getTime());
 }

} /*Now : Wed Feb 18 13:52:43 PST 2009 Date after decrement: Sun Jan 18 13:52:43 PST 2009

  • /



 </source>
   
  
 
  



Match Date

   <source lang="java">
    

public class MatchDates {

 public static void main(String args[]) {
   isDateValid("04-02-1995");
   isDateValid("15-42-1994");
   isDateValid("April fourth nineteen ninety nine");
   isDateValid("15-42-20001");
   isDateValid("02-02-20001");
   isDateValid("05-02-02");
   isDateValid("04-01-jexp");
 }
 public static boolean isDateValid(String date) {
   boolean retval = false;
   String datePattern = "\\d{1,2}-\\d{1,2}-\\d{4}";
   retval = date.matches(datePattern);
   String msg = "NO MATCH: pattern:" + date
       + "\r\n             regexLength: " + datePattern;
   if (retval) {
     msg = "MATCH   : pattern:" + date
         + "\r\n             regexLength: " + datePattern;
   }
   System.out.println(msg + "\r\n");
   return retval;
 }

}




 </source>
   
  
 
  



Monitored GregorianCalendar

   <source lang="java">
  

import java.util.*; /**

* @author Matthew D. Hicks
*
*/

public class MonitoredGregorianCalendar extends GregorianCalendar {

 private ArrayList listeners;
 
 private boolean blocked;
 
 public MonitoredGregorianCalendar() {
   super();
   listeners = new ArrayList();
 }
 
 public MonitoredGregorianCalendar(int year, int month, int dayOfMonth) {
   super(year, month, dayOfMonth);
   listeners = new ArrayList();
 }
 
 public MonitoredGregorianCalendar(int year, int month, int dayOfMonth, int hourOfDay, int minute) {
   super(year, month, dayOfMonth, hourOfDay, minute);
   listeners = new ArrayList();
 }
 
 public MonitoredGregorianCalendar(int year, int month, int dayOfMonth, int hourOfDay, int minute, int second) {
   super(year, month, dayOfMonth, hourOfDay, minute, second);
   listeners = new ArrayList();
 }
 
 public MonitoredGregorianCalendar(Locale aLocale) {
   super(aLocale);
   listeners = new ArrayList();
 }
 
 public MonitoredGregorianCalendar(TimeZone zone) {
   super(zone);
   listeners = new ArrayList();
 }
 
 public void add(int field, int amount) {
   if (!blocked) {
     blocked = true;
     super.add(field, amount);
     blocked = false;
     changed(CalendarChangeListener.TYPE_ADD, field, amount);
   } else {
     super.add(field, amount);
   }
 }
 
 public void roll(int field, boolean up) {
   if (!blocked) {
     blocked = true;
     super.roll(field, up);
     blocked = false;
     int amount = 0;
     if (up) amount = 1;
     changed(CalendarChangeListener.TYPE_ROLL, field, amount);
   } else {
     super.roll(field, up);
   }
 }
 
 public void roll(int field, int amount) {
   if (!blocked) {
     blocked = true;
     super.roll(field, amount);
     blocked = false;
     changed(CalendarChangeListener.TYPE_ROLL, field, amount);
   } else {
     super.roll(field, amount);
   }
 }
 
 public void setGregorianChange(Date date) {
   if (!blocked) {
     blocked = true;
     super.setGregorianChange(date);
     blocked = false;
     changed(CalendarChangeListener.TYPE_SET, CalendarChangeListener.TIME_IN_MILLIS, date.getTime());
   } else {
     super.setGregorianChange(date);
   }
 }
 
 public void setTimeZone(TimeZone zone) {
   if (!blocked) {
     blocked = true;
     super.setTimeZone(zone);
     blocked = false;
     changed(CalendarChangeListener.TYPE_SET, CalendarChangeListener.TIME_ZONE, zone.getRawOffset());
   } else {
     super.setTimeZone(zone);
   }
 }
 
 public void set(int field, int value) {
   if (!blocked) {
     blocked = true;
     super.set(field, value);
     blocked = false;
     changed(CalendarChangeListener.TYPE_SET, field, value);
   } else {
     super.set(field, value);
   }
 }
 
 public void setFirstDayOfWeek(int value) {
   if (!blocked) {
     blocked = true;
     super.setFirstDayOfWeek(value);
     blocked = false;
     changed(CalendarChangeListener.TYPE_SET, CalendarChangeListener.FIRST_DAY_OF_WEEK, value);
   } else {
     super.setFirstDayOfWeek(value);
   }
 }
 
 public void setLenient(boolean lenient) {
   if (!blocked) {
     blocked = true;
     super.setLenient(lenient);
     blocked = false;
     int amount = 0;
     if (lenient) amount = 1;
     changed(CalendarChangeListener.TYPE_SET, CalendarChangeListener.LENIENT, amount);
   } else {
     super.setLenient(lenient);
   }
 }
 
 public void setMinimalDaysInFirstWeek(int value) {
   if (!blocked) {
     blocked = true;
     super.setMinimalDaysInFirstWeek(value);
     blocked = false;
     changed(CalendarChangeListener.TYPE_SET, CalendarChangeListener.MINIMAL_DAYS_IN_FIRST_WEEK, value);
   } else {
     super.setMinimalDaysInFirstWeek(value);
   }
 }
 
 public void setTimeInMillis(long millis) {
   if (!blocked) {
     blocked = true;
     super.setTimeInMillis(millis);
     blocked = false;
     changed(CalendarChangeListener.TYPE_SET, CalendarChangeListener.TIME_IN_MILLIS, millis);
   } else {
     super.setTimeInMillis(millis);
   }
 }
 
 private void changed(int type, int field, long value) {
   if ((listeners != null) && (!blocked)) {
     for (int i = 0; i < listeners.size(); i++) {
       ((CalendarChangeListener)listeners.get(i)).changed(this, type, field, value);
     }
   }
 }
 
 public void addListener(CalendarChangeListener listener) {
   listeners.add(listener);
 }

}

/**

* @author Matthew D. Hicks
*
*/

interface CalendarChangeListener {

 public static final int TYPE_ADD = 1;
 public static final int TYPE_ROLL = 2;
 public static final int TYPE_SET = 3;
 
 public static final int TIME_ZONE = 1;
 public static final int FIRST_DAY_OF_WEEK = 2;
 public static final int LENIENT = 3;
 public static final int MINIMAL_DAYS_IN_FIRST_WEEK = 4;
 public static final int TIME_IN_MILLIS = 5;
 
 /**
  * This method is called when a MonitoredGregorianCalendar changes.
  * 
  * @param c
  *    A reference to the MonitoredGregorianCalendar that has been changed.
  * @param type
  *    The type of change that occurred:
  *      TYPE_ADD, TYPE_ROLL, or TYPE_SET
  * @param field
  *    The field that was changed either a Calendar type or:
  *      TIME_ZONE, FIRST_DAY_OF_WEEK, LENIENT, MINIMAL_DAYS_IN_FIRST_WEEK, or TIME_IN_MILLIS
  * @param value
  *    The value associated with the change.
  */
 public void changed(MonitoredGregorianCalendar c, int type, int field, long value);

}


 </source>
   
  
 
  



Output current time: %tc

   <source lang="java">
    

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);
 }

}



 </source>
   
  
 
  



Parse a String to obtain a Date/GregorianCalendar object

   <source lang="java">
    

import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; public class Main {

 public static Calendar parseTimestamp(String timestamp) throws Exception {
   SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss", Locale.US);
   Date d = sdf.parse(timestamp);
   Calendar cal = Calendar.getInstance();
   cal.setTime(d);
   return cal;
 }
 public static void main(String a[]) throws Exception {
   String timestampToParse = "24-Feb-2009 17:39:35";
   System.out.println("Timestamp : " + timestampToParse);
   SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   System.out.println("Calendar : " + sdf.format(parseTimestamp(timestampToParse).getTime()));
 }

}



 </source>
   
  
 
  



Pass the year information to the calendar object

   <source lang="java">
    
import java.util.Calendar;

public class Main {

 public static void main(String[] argv) throws Exception {
   int year = 2004;
   Calendar calendar = Calendar.getInstance();
   calendar.set(Calendar.YEAR, year);
 }

}




 </source>
   
  
 
  



RFC date format

   <source lang="java">
  

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);
   }

}


 </source>
   
  
 
  



Set with GregorianCalendar.YEAR, MONTH and DATE

   <source lang="java">
    

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);
   gc.getTime();
 }

}



 </source>
   
  
 
  



Show dates before 1970

   <source lang="java">
    

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

import java.util.Calendar; import java.util.GregorianCalendar; /**

* Show dates before 1970.
* 
* @author Ian F. Darwin, http://www.darwinsys.ru/
* @version $Id: DatePrint1.java,v 1.3 2004/02/09 03:33:46 ian Exp $
*/

public class DatePrint1 {

 public static void main(String[] argv) {
   //+
   Calendar c = new GregorianCalendar(1918, 10, 11);
   System.out.println(c.get(Calendar.DAY_OF_MONTH) + " "
       + c.get(Calendar.MONTH) + ", " + c.get(Calendar.YEAR) + " "
       + c.get(Calendar.ERA));
   //-
 }

}




 </source>
   
  
 
  



Show some calendar calculations

   <source lang="java">
    

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

import java.util.Calendar; /**

* Show some calendar calculations.
* 
* @author Ian F. Darwin, http://www.darwinsys.ru/
* @version $Id: CalCalcs.java,v 1.3 2004/02/09 03:33:45 ian Exp $
*/

public class CalCalcs {

 public static void main(String[] argv) {
   //+
   Calendar c = Calendar.getInstance();
   System.out.println("I got a " + c.getClass());
   c.set(1951, 03, 24, 12, 30, 0);
   System.out.println("I set it to " + c.getTime().toString());
   System.out
       .println("I actually set the year to " + c.get(Calendar.YEAR));
   System.out.println("In milliseconds, that"s " + c.getTime().getTime());
   System.out.println("Or, in seconds, " + c.getTime().getTime() / 1000);
   //-
 }

}




 </source>
   
  
 
  



Show some date uses

   <source lang="java">
    

import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Date; /** Show some date uses */ public class DateParse2 {

 public static void main(String[] args) {
   //+
   SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
   String input[] = { "BD: 1913-10-01 Vancouver, B.C.",
       "MD: 1948-03-01 Ottawa, ON", "DD: 1983-06-06 Toronto, ON" };
   for (int i = 0; i < input.length; i++) {
     String aLine = input[i];
     String action;
     switch (aLine.charAt(0)) {
     case "B":
       action = "Born";
       break;
     case "M":
       action = "Married";
       break;
     case "D":
       action = "Died";
       break;
     // others...
     default:
       System.err.println("Invalid code in " + aLine);
       continue;
     }
     int p = aLine.indexOf(" ");
     ParsePosition pp = new ParsePosition(p);
     Date d = formatter.parse(aLine, pp);
     if (d == null) {
       System.err.println("Invalid date in " + aLine);
       continue;
     }
     String location = aLine.substring(pp.getIndex());
     System.out.println(action + " on " + d + " in " + location);
   }
   //-
 }

}




 </source>
   
  
 
  



Show some date uses 1

   <source lang="java">
    

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

import java.text.SimpleDateFormat; import java.util.Date; /** Show some date uses */ public class DateDemo {

 public static void main(String[] args) {
   //+
   Date dNow = new Date();
   /* Simple, Java 1.0 date printing */
   System.out.println("It is now " + dNow.toString());
   // Use a SimpleDateFormat to print the date our way.
   SimpleDateFormat formatter = new SimpleDateFormat(
       "E yyyy.MM.dd "at" hh:mm:ss a zzz");
   System.out.println("It is " + formatter.format(dNow));
   //-
 }

}




 </source>
   
  
 
  



Show use of Calendar get() method with various parameters

   <source lang="java">
    

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

import java.util.Calendar; /** Show use of Calendar get() method with various parameters. */ public class DayWeek {

 public static void main(String[] av) {
   //+
   Calendar c = Calendar.getInstance(); // today
   System.out.println("Year: " + c.get(Calendar.YEAR));
   System.out.println("Month: " + c.get(Calendar.MONTH));
   System.out.println("Day: " + c.get(Calendar.DAY_OF_MONTH));
   System.out.println("Day of week = " + c.get(Calendar.DAY_OF_WEEK));
   System.out.println("Day of year = " + c.get(Calendar.DAY_OF_YEAR));
   System.out.println("Week in Year: " + c.get(Calendar.WEEK_OF_YEAR));
   System.out.println("Week in Month: " + c.get(Calendar.WEEK_OF_MONTH));
   System.out.println("Day of Week in Month: "
       + c.get(Calendar.DAY_OF_WEEK_IN_MONTH));
   System.out.println("Hour: " + c.get(Calendar.HOUR));
   System.out.println("AM or PM: " + c.get(Calendar.AM_PM));
   System.out.println("Hour (24-hour clock): "
       + c.get(Calendar.HOUR_OF_DAY));
   System.out.println("Minute: " + c.get(Calendar.MINUTE));
   System.out.println("Second: " + c.get(Calendar.SECOND));
   //-
 }

}




 </source>
   
  
 
  



Show use of Calendar objects

   <source lang="java">
    

import java.util.Calendar; import java.util.GregorianCalendar; /** Show use of Calendar objects */ public class GregCalDemo {

 public static void main(String[] av) {
   //+
   GregorianCalendar d1 = new GregorianCalendar(1986, 04, 05); // May 5
   GregorianCalendar d2 = new GregorianCalendar(); // today
   Calendar d3 = Calendar.getInstance(); // today
   System.out.println("It was then " + d1.getTime());
   System.out.println("It is now " + d2.getTime());
   System.out.println("It is now " + d3.getTime());
   d3.set(Calendar.YEAR, 1915);
   d3.set(Calendar.MONTH, Calendar.APRIL);
   d3.set(Calendar.DAY_OF_MONTH, 12);
   System.out.println("D3 set to " + d3.getTime());
   //-
 }

}




 </source>
   
  
 
  



Subtract 1 year from the calendar

   <source lang="java">
    

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   Calendar cal = Calendar.getInstance();
   System.out.println("Today : " + cal.getTime());
   // Subtract 1 year from the calendar
   cal.add(Calendar.YEAR, -1);
   System.out.println("1 year ago: " + cal.getTime());
 }

}



 </source>
   
  
 
  



Subtract 30 days from the calendar

   <source lang="java">
    

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   Calendar cal = Calendar.getInstance();
   System.out.println("Today : " + cal.getTime());
   // Subtract 30 days from the calendar
   cal.add(Calendar.DATE, -30);
   System.out.println("30 days ago: " + cal.getTime());
 }

}



 </source>
   
  
 
  



Subtract days from current date using Calendar.add method

   <source lang="java">
    

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   Calendar now = Calendar.getInstance();
   System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1) + "-"
       + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
   now = Calendar.getInstance();
   now.add(Calendar.DATE, -10);
   System.out.println("date before 10 days : " + (now.get(Calendar.MONTH) + 1) + "-"
       + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
 }

} /* Current date : 2-20-2009 date before 10 days : 2-10-2009

  • /



 </source>
   
  
 
  



Subtract hours from current date using Calendar.add method

   <source lang="java">
    

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   Calendar now = Calendar.getInstance();
   System.out.println("Current Date : " + (now.get(Calendar.MONTH) + 1) + "-"
       + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
   System.out.println("Current time : " + now.get(Calendar.HOUR_OF_DAY) + ":"
       + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));
   now = Calendar.getInstance();
   now.add(Calendar.HOUR, -3);
   System.out.println("Time before 3 hours : " + now.get(Calendar.HOUR_OF_DAY) + ":"
       + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));
 }

}



 </source>
   
  
 
  



Subtract minutes from current date using Calendar.add method

   <source lang="java">
    

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   Calendar now = Calendar.getInstance();
   System.out.println("Current time : " + now.get(Calendar.HOUR_OF_DAY) + ":"
       + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));
   now = Calendar.getInstance();
   now.add(Calendar.MINUTE, -50);
   System.out.println("Time before 50 minutes : " + now.get(Calendar.HOUR_OF_DAY) + ":"
       + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));
 }

}



 </source>
   
  
 
  



Subtract months from current date using Calendar.add method

   <source lang="java">
    

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   Calendar now = Calendar.getInstance();
   System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1) + "-"
       + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
   now = Calendar.getInstance();
   now.add(Calendar.MONTH, -5);
   System.out.println("date before 5 months : " + (now.get(Calendar.MONTH) + 1) + "-"
       + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
 }

}



 </source>
   
  
 
  



Subtract seconds from current time using Calendar.add method

   <source lang="java">
    

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   Calendar now = Calendar.getInstance();
   System.out.println("Current time : " + now.get(Calendar.HOUR_OF_DAY) + ":"
       + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));
   now = Calendar.getInstance();
   now.add(Calendar.SECOND, -50);
   System.out.println("Time before 50 minutes : " + now.get(Calendar.HOUR_OF_DAY) + ":"
       + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));  }

}



 </source>
   
  
 
  



Subtract week from current date

   <source lang="java">
    

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   Calendar now = Calendar.getInstance();
   System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1) + "-"
       + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
   System.out.println("Current week of month is : " + now.get(Calendar.WEEK_OF_MONTH));
   System.out.println("Current week of year is : " + now.get(Calendar.WEEK_OF_YEAR));
   now = Calendar.getInstance();
   now.add(Calendar.WEEK_OF_YEAR, -50);
   System.out.println("date before 50 weeks : " + (now.get(Calendar.MONTH) + 1) + "-"
       + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
 }

}



 </source>
   
  
 
  



Subtract year from current date

   <source lang="java">
    

import java.util.Calendar; public class Main {

 public static void main(String[] args) {
   Calendar now = Calendar.getInstance();
   System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1) + "-"
       + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
   now = Calendar.getInstance();
   now.add(Calendar.YEAR, -100);
   System.out.println("date before 100 years : " + (now.get(Calendar.MONTH) + 1) + "-"
       + now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR));
 }

}



 </source>
   
  
 
  



Swing: Date Time Editor

   <source lang="java">
    

/* Swing, Second Edition by Matthew Robinson, Pavel Vorobiev

  • /

import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.text.DateFormat; import java.text.FieldPosition; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.ruparator; import java.util.Date; import java.util.Iterator; import java.util.NoSuchElementException; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.SwingConstants; import javax.swing.border.EmptyBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.plaf.basic.BasicArrowButton; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.Caret; import javax.swing.text.DefaultEditorKit; import javax.swing.text.JTextComponent; import javax.swing.text.Keymap; import javax.swing.text.PlainDocument; import javax.swing.text.TextAction; public class DateTimeEditor extends JPanel {

 public static final long ONE_SECOND = 1000;
 public static final long ONE_MINUTE = 60 * ONE_SECOND;
 public static final long ONE_HOUR = 60 * ONE_MINUTE;
 public static final long ONE_DAY = 24 * ONE_HOUR;
 public static final long ONE_WEEK = 7 * ONE_DAY;
 public final static int TIME = 0;
 public final static int DATE = 1;
 public final static int DATETIME = 2;
 private int m_timeOrDateType;
 private int m_lengthStyle;
 private DateFormat m_format;
 private Calendar m_calendar = Calendar.getInstance();
 private ArrayList m_fieldPositions = new ArrayList();
 private Date m_lastDate = new Date();
 private Caret m_caret;
 private int m_curField = -1;
 private JTextField m_textField;
 private Spinner m_spinner;
 private AbstractAction m_upAction = new UpDownAction(1, "up");
 private AbstractAction m_downAction = new UpDownAction(-1, "down");
 private boolean m_settingDateText = false; // BUG FIX
 private int[] m_fieldTypes = { DateFormat.ERA_FIELD, DateFormat.YEAR_FIELD,
     DateFormat.MONTH_FIELD, DateFormat.DATE_FIELD,
     DateFormat.HOUR_OF_DAY1_FIELD, DateFormat.HOUR_OF_DAY0_FIELD,
     DateFormat.MINUTE_FIELD, DateFormat.SECOND_FIELD,
     DateFormat.MILLISECOND_FIELD, DateFormat.DAY_OF_WEEK_FIELD,
     DateFormat.DAY_OF_YEAR_FIELD,
     DateFormat.DAY_OF_WEEK_IN_MONTH_FIELD,
     DateFormat.WEEK_OF_YEAR_FIELD, DateFormat.WEEK_OF_MONTH_FIELD,
     DateFormat.AM_PM_FIELD, DateFormat.HOUR1_FIELD,
     DateFormat.HOUR0_FIELD };
 public DateTimeEditor() {
   m_timeOrDateType = DATETIME;
   m_lengthStyle = DateFormat.SHORT;
   init();
 }
 public DateTimeEditor(int timeOrDateType) {
   m_timeOrDateType = timeOrDateType;
   m_lengthStyle = DateFormat.FULL;
   init();
 }
 public DateTimeEditor(int timeOrDateType, int lengthStyle) {
   m_timeOrDateType = timeOrDateType;
   m_lengthStyle = lengthStyle;
   init();
 }
 private void init() {
   setLayout(new BorderLayout());
   m_textField = new JTextField();
   m_textField.setDocument(new DateTimeDocument()); // BUG FIX
   m_spinner = new Spinner();
   m_spinner.getIncrementButton().addActionListener(m_upAction);
   m_spinner.getDecrementButton().addActionListener(m_downAction);
   add(m_textField, "Center");
   add(m_spinner, "East");
   m_caret = m_textField.getCaret();
   m_caret.addChangeListener(new ChangeListener() {
     public void stateChanged(ChangeEvent evt) {
       setCurField();
     }
   });
   setupKeymap();
   reinit();
 }
 protected class DateTimeDocument extends PlainDocument {
   public void insertString(int offset, String str, AttributeSet a)
       throws BadLocationException {
     if (m_settingDateText)
       super.insertString(offset, str, a);
   }
 } // BUG FIX
 public int getTimeOrDateType() {
   return m_timeOrDateType;
 }
 public void setTimeOrDateType(int timeOrDateType) {
   m_timeOrDateType = timeOrDateType;
   reinit();
 }
 public int getLengthStyle() {
   return m_lengthStyle;
 }
 public void setLengthStyle(int lengthStyle) {
   m_lengthStyle = lengthStyle;
   reinit();
 }
 public Date getDate() {
   return (m_lastDate);
 }
 // public void setDate(Date date)
 // {
 //    m_lastDate = date;
 //    m_calendar.setTime(m_lastDate);
 //    m_textField.setText(m_format.format(m_lastDate));
 //    getFieldPositions();
 // }
 public void setDate(Date date) {
   m_lastDate = date;
   m_calendar.setTime(m_lastDate);
   m_settingDateText = true;
   m_textField.setText(m_format.format(m_lastDate));
   m_settingDateText = false;
   getFieldPositions();
 } // BUG FIX
 private int getFieldBeginIndex(int fieldNum) {
   int beginIndex = -1;
   for (Iterator iter = m_fieldPositions.iterator(); iter.hasNext();) {
     FieldPosition fieldPos = (FieldPosition) iter.next();
     if (fieldPos.getField() == fieldNum) {
       beginIndex = fieldPos.getBeginIndex();
       break;
     }
   }
   return (beginIndex);
 }
 private FieldPosition getFieldPosition(int fieldNum) {
   FieldPosition result = null;
   for (Iterator iter = m_fieldPositions.iterator(); iter.hasNext();) {
     FieldPosition fieldPosition = (FieldPosition) iter.next();
     if (fieldPosition.getField() == fieldNum) {
       result = fieldPosition;
       break;
     }
   }
   return (result);
 }
 private void reinit() {
   setupFormat();
   setDate(m_lastDate);
   m_caret.setDot(0);
   setCurField();
   repaint();
 }
 protected void setupFormat() {
   switch (m_timeOrDateType) {
   case TIME:
     m_format = DateFormat.getTimeInstance(m_lengthStyle);
     break;
   case DATE:
     m_format = DateFormat.getDateInstance(m_lengthStyle);
     break;
   case DATETIME:
     m_format = DateFormat.getDateTimeInstance(m_lengthStyle,
         m_lengthStyle);
     break;
   }
 }
 protected class UpDownAction extends AbstractAction {
   int m_direction; // +1 = up; -1 = down
   public UpDownAction(int direction, String name) {
     super(name);
     m_direction = direction;
   }
   public void actionPerformed(ActionEvent evt) {
     if (!this.isEnabled())
       return;
     boolean dateSet = true;
     switch (m_curField) {
     case DateFormat.AM_PM_FIELD:
       m_lastDate.setTime(m_lastDate.getTime()
           + (m_direction * 12 * ONE_HOUR));
       break;
     case DateFormat.DATE_FIELD:
     case DateFormat.DAY_OF_WEEK_FIELD:
     case DateFormat.DAY_OF_WEEK_IN_MONTH_FIELD:
     case DateFormat.DAY_OF_YEAR_FIELD:
       m_lastDate.setTime(m_lastDate.getTime()
           + (m_direction * ONE_DAY));
       break;
     case DateFormat.ERA_FIELD:
       dateSet = false;
       break;
     case DateFormat.HOUR0_FIELD:
     case DateFormat.HOUR1_FIELD:
     case DateFormat.HOUR_OF_DAY0_FIELD:
     case DateFormat.HOUR_OF_DAY1_FIELD:
       m_lastDate.setTime(m_lastDate.getTime()
           + (m_direction * ONE_HOUR));
       break;
     case DateFormat.MILLISECOND_FIELD:
       m_lastDate.setTime(m_lastDate.getTime() + (m_direction * 1));
       break;
     case DateFormat.MINUTE_FIELD:
       m_lastDate.setTime(m_lastDate.getTime()
           + (m_direction * ONE_MINUTE));
       break;
     case DateFormat.MONTH_FIELD:
       m_calendar.set(Calendar.MONTH, m_calendar.get(Calendar.MONTH)
           + m_direction);
       m_lastDate = m_calendar.getTime();
       break;
     case DateFormat.SECOND_FIELD:
       m_lastDate.setTime(m_lastDate.getTime()
           + (m_direction * ONE_SECOND));
       break;
     case DateFormat.WEEK_OF_MONTH_FIELD:
       m_calendar.set(Calendar.WEEK_OF_MONTH, m_calendar
           .get(Calendar.WEEK_OF_MONTH)
           + m_direction);
       m_lastDate = m_calendar.getTime();
       break;
     case DateFormat.WEEK_OF_YEAR_FIELD:
       m_calendar.set(Calendar.WEEK_OF_MONTH, m_calendar
           .get(Calendar.WEEK_OF_MONTH)
           + m_direction);
       m_lastDate = m_calendar.getTime();
       break;
     case DateFormat.YEAR_FIELD:
       m_calendar.set(Calendar.YEAR, m_calendar.get(Calendar.YEAR)
           + m_direction);
       m_lastDate = m_calendar.getTime();
       break;
     default:
       dateSet = false;
     }
     if (dateSet) {
       int fieldId = m_curField;
       setDate(m_lastDate);
       FieldPosition fieldPosition = getFieldPosition(fieldId);
       m_caret.setDot(fieldPosition.getBeginIndex());
       m_textField.requestFocus();
       repaint();
     }
   }
 }
 protected class BackwardAction extends TextAction {
   BackwardAction(String name) {
     super(name);
   }
   public void actionPerformed(ActionEvent e) {
     JTextComponent target = getTextComponent(e);
     if (target != null) {
       int dot = target.getCaretPosition();
       if (dot > 0) {
         FieldPosition position = getPrevField(dot);
         if (position != null)
           target.setCaretPosition(position.getBeginIndex());
         else {
           position = getFirstField();
           if (position != null)
             target.setCaretPosition(position.getBeginIndex());
         }
       } else
         target.getToolkit().beep();
       target.getCaret().setMagicCaretPosition(null);
     }
   }
 }
 protected class ForwardAction extends TextAction {
   ForwardAction(String name) {
     super(name);
   }
   public void actionPerformed(ActionEvent e) {
     JTextComponent target = getTextComponent(e);
     if (target != null) {
       FieldPosition position = getNextField(target.getCaretPosition());
       if (position != null)
         target.setCaretPosition(position.getBeginIndex());
       else {
         position = getLastField();
         if (position != null)
           target.setCaretPosition(position.getBeginIndex());
       }
       target.getCaret().setMagicCaretPosition(null);
     }
   }
 }
 protected class BeginAction extends TextAction {
   BeginAction(String name) {
     super(name);
   }
   public void actionPerformed(ActionEvent e) {
     JTextComponent target = getTextComponent(e);
     if (target != null) {
       FieldPosition position = getFirstField();
       if (position != null)
         target.setCaretPosition(position.getBeginIndex());
     }
   }
 }
 protected class EndAction extends TextAction {
   EndAction(String name) {
     super(name);
   }
   public void actionPerformed(ActionEvent e) {
     JTextComponent target = getTextComponent(e);
     if (target != null) {
       FieldPosition position = getLastField();
       if (position != null)
         target.setCaretPosition(position.getBeginIndex());
     }
   }
 }
 protected void setupKeymap() {
   Keymap keymap = m_textField.addKeymap("DateTimeKeymap", null);
   keymap.addActionForKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0),
       m_upAction);
   keymap.addActionForKeyStroke(KeyStroke
       .getKeyStroke(KeyEvent.VK_DOWN, 0), m_downAction);
   keymap.addActionForKeyStroke(KeyStroke
       .getKeyStroke(KeyEvent.VK_LEFT, 0), new BackwardAction(
       DefaultEditorKit.backwardAction));
   keymap.addActionForKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,
       0), new ForwardAction(DefaultEditorKit.forwardAction));
   keymap.addActionForKeyStroke(KeyStroke
       .getKeyStroke(KeyEvent.VK_HOME, 0), new BeginAction(
       DefaultEditorKit.beginAction));
   keymap.addActionForKeyStroke(
       KeyStroke.getKeyStroke(KeyEvent.VK_END, 0), new EndAction(
           DefaultEditorKit.endAction));
   m_textField.setKeymap(keymap);
 }
 private void getFieldPositions() {
   m_fieldPositions.clear();
   for (int ctr = 0; ctr < m_fieldTypes.length; ++ctr) {
     int fieldId = m_fieldTypes[ctr];
     FieldPosition fieldPosition = new FieldPosition(fieldId);
     StringBuffer formattedField = new StringBuffer();
     m_format.format(m_lastDate, formattedField, fieldPosition);
     if (fieldPosition.getEndIndex() > 0)
       m_fieldPositions.add(fieldPosition);
   }
   m_fieldPositions.trimToSize();
   Collections.sort(m_fieldPositions, new Comparator() {
     public int compare(Object o1, Object o2) {
       return (((FieldPosition) o1).getBeginIndex() - ((FieldPosition) o2)
           .getBeginIndex());
     }
   });
 }
 private FieldPosition getField(int caretLoc) {
   FieldPosition fieldPosition = null;
   for (Iterator iter = m_fieldPositions.iterator(); iter.hasNext();) {
     FieldPosition chkFieldPosition = (FieldPosition) iter.next();
     if ((chkFieldPosition.getBeginIndex() <= caretLoc)
         && (chkFieldPosition.getEndIndex() > caretLoc)) {
       fieldPosition = chkFieldPosition;
       break;
     }
   }
   return (fieldPosition);
 }
 private FieldPosition getPrevField(int caretLoc) {
   FieldPosition fieldPosition = null;
   for (int ctr = m_fieldPositions.size() - 1; ctr > -1; --ctr) {
     FieldPosition chkFieldPosition = (FieldPosition) m_fieldPositions
         .get(ctr);
     if (chkFieldPosition.getEndIndex() <= caretLoc) {
       fieldPosition = chkFieldPosition;
       break;
     }
   }
   return (fieldPosition);
 }
 private FieldPosition getNextField(int caretLoc) {
   FieldPosition fieldPosition = null;
   for (Iterator iter = m_fieldPositions.iterator(); iter.hasNext();) {
     FieldPosition chkFieldPosition = (FieldPosition) iter.next();
     if (chkFieldPosition.getBeginIndex() > caretLoc) {
       fieldPosition = chkFieldPosition;
       break;
     }
   }
   return (fieldPosition);
 }
 private FieldPosition getFirstField() {
   FieldPosition result = null;
   try {
     result = ((FieldPosition) m_fieldPositions.get(0));
   } catch (NoSuchElementException ex) {
   }
   return (result);
 }
 private FieldPosition getLastField() {
   FieldPosition result = null;
   try {
     result = ((FieldPosition) m_fieldPositions.get(m_fieldPositions
         .size() - 1));
   } catch (NoSuchElementException ex) {
   }
   return (result);
 }
 private void setCurField() {
   FieldPosition fieldPosition = getField(m_caret.getDot());
   if (fieldPosition != null) {
     if (m_caret.getDot() != fieldPosition.getBeginIndex())
       m_caret.setDot(fieldPosition.getBeginIndex());
   } else {
     fieldPosition = getPrevField(m_caret.getDot());
     if (fieldPosition != null)
       m_caret.setDot(fieldPosition.getBeginIndex());
     else {
       fieldPosition = getFirstField();
       if (fieldPosition != null)
         m_caret.setDot(fieldPosition.getBeginIndex());
     }
   }
   if (fieldPosition != null)
     m_curField = fieldPosition.getField();
   else
     m_curField = -1;
 }
 public void setEnabled(boolean enable) {
   m_textField.setEnabled(enable);
   m_spinner.setEnabled(enable);
 }
 public boolean isEnabled() {
   return (m_textField.isEnabled() && m_spinner.isEnabled());
 }
 public static void main(String[] args) {
   JFrame frame = new JFrame();
   frame.addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent evt) {
       System.exit(0);
     }
   });
   JPanel panel = new JPanel(new BorderLayout());
   panel.setBorder(new EmptyBorder(5, 5, 5, 5));
   frame.setContentPane(panel);
   final DateTimeEditor field = new DateTimeEditor(
       DateTimeEditor.DATETIME, DateFormat.FULL);
   panel.add(field, "North");
   JPanel buttonBox = new JPanel(new GridLayout(2, 2));
   JButton showDateButton = new JButton("Show Date");
   buttonBox.add(showDateButton);
   final JComboBox timeDateChoice = new JComboBox();
   timeDateChoice.addItem("Time");
   timeDateChoice.addItem("Date");
   timeDateChoice.addItem("Date/Time");
   timeDateChoice.setSelectedIndex(2);
   timeDateChoice.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent evt) {
       field.setTimeOrDateType(timeDateChoice.getSelectedIndex());
     }
   });
   buttonBox.add(timeDateChoice);
   JButton toggleButton = new JButton("Toggle Enable");
   buttonBox.add(toggleButton);
   showDateButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent evt) {
       System.out.println(field.getDate());
     }
   });
   toggleButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent evt) {
       field.setEnabled(!field.isEnabled());
     }
   });
   panel.add(buttonBox, "South");
   final JComboBox lengthStyleChoice = new JComboBox();
   lengthStyleChoice.addItem("Full");
   lengthStyleChoice.addItem("Long");
   lengthStyleChoice.addItem("Medium");
   lengthStyleChoice.addItem("Short");
   lengthStyleChoice.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent evt) {
       field.setLengthStyle(lengthStyleChoice.getSelectedIndex());
     }
   });
   buttonBox.add(lengthStyleChoice);
   frame.pack();
   Dimension dim = frame.getToolkit().getScreenSize();
   frame.setLocation(dim.width / 2 - frame.getWidth() / 2, dim.height / 2
       - frame.getHeight() / 2);
   frame.show();
 }

} class Spinner extends JPanel {

  private int m_orientation = SwingConstants.VERTICAL;
  private BasicArrowButton m_incrementButton;
  private BasicArrowButton m_decrementButton;
  public Spinner() { createComponents(); }
  public Spinner(int orientation)
  {
     m_orientation = orientation;
     createComponents();
  }
  public void setEnabled(boolean enable)
  {
     m_incrementButton.setEnabled(enable);
     m_decrementButton.setEnabled(enable);
  }
  public boolean isEnabled()
  {
     return (m_incrementButton.isEnabled() &&
        m_decrementButton.isEnabled());
  }
  
  protected void createComponents()
  {
     if (m_orientation == SwingConstants.VERTICAL)
     {
        setLayout(new GridLayout(2, 1));
        m_incrementButton = new BasicArrowButton(
           SwingConstants.NORTH);
        m_decrementButton = new BasicArrowButton(
           SwingConstants.SOUTH);
        add(m_incrementButton);
        add(m_decrementButton);
     }
     else if (m_orientation == SwingConstants.HORIZONTAL)
     {
        setLayout(new GridLayout(1, 2));
        m_incrementButton = new BasicArrowButton(
           SwingConstants.EAST);
        m_decrementButton = new BasicArrowButton(
           SwingConstants.WEST);
        add(m_decrementButton);
        add(m_incrementButton);
     }
  }
  public JButton getIncrementButton() { 
     return (m_incrementButton); }
  public JButton getDecrementButton() { 
     return (m_decrementButton); }
  public static void main(String[] args)
  {
     JFrame frame = new JFrame();
     JPanel panel = (JPanel) frame.getContentPane();
     panel.setLayout(new BorderLayout());
     JTextField  field = new JTextField(20);
     Spinner spinner = new Spinner();
     panel.add(field, "Center");
     panel.add(spinner, "East");
     Dimension dim = frame.getToolkit().getScreenSize();
     frame.setLocation(dim.width/2 - frame.getWidth()/2,
        dim.height/2 - frame.getHeight()/2);
     frame.pack();
     frame.show();
  }

}




 </source>
   
  
 
  



The best way to format a date/time is to use

   <source lang="java">
    

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

import java.text.DateFormat; import java.util.Date; import java.util.Locale; /**

* The "best" way to format a date/time is to use the DateFormat.getInstance()
* method, which will be localized automatically.
* 
* @version $Id: DateFormatBest.java,v 1.1 2004/03/03 17:22:14 ian Exp $
*/

public class DateFormatBest {

 public static void main(String[] args) {
   Date today = new Date();
   DateFormat df = DateFormat.getInstance();
   System.out.println(df.format(today));
   DateFormat df_fr = DateFormat.getDateInstance(DateFormat.FULL,
       Locale.FRENCH);
   System.out.println(df_fr.format(today));
 }

}




 </source>
   
  
 
  



TimeComputation for processing sqrt and Input and Output operations.

   <source lang="java">
    

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

import java.io.BufferedOutputStream; import java.io.DataOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.text.DecimalFormat; /**

* TimeComputation for processing sqrt and Input and Output operations.
* 
* @author Ian Darwin, http://www.darwinsys.ru/
* @version $Id: TimeComputation.java,v 1.7 2004/02/09 03:33:46 ian Exp $
*/

public class TimeComputation {

 public static void main(String[] argv) {
   try {
     new TimeComputation().run();
   } catch (IOException e) {
     System.err.println(e);
   }
 }
 public void run() throws IOException {
   DataOutputStream n = new DataOutputStream(new BufferedOutputStream(
       new FileOutputStream("jexp")));
   long t0, t1;
   System.out.println("Java Starts at "
       + (t0 = System.currentTimeMillis()));
   double k;
   for (int i = 0; i < 100000; i++) {
     k = 2.1 * Math.sqrt((double) i);
     n.writeDouble(k);
   }
   System.out.println("Java Ends at " + (t1 = System.currentTimeMillis()));
   double deltaT = t1 - t0;
   System.out.println("This run took "
       + DecimalFormat.getInstance().format(deltaT / 1000.)
       + " seconds.");
 }

}




 </source>
   
  
 
  



Trivial class to show use of Date and Calendar objects

   <source lang="java">
    

import java.text.DateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; /** Trivial class to show use of Date & Calendar objects */ public class DateUse {

 /** Typical main method ("main program") declaration */
 public static void main(String[] av) {
   Locale l1 = new Locale("en", "US"), l2 = new Locale("es", "ES");
   // Create a Date object for May 5, 1986
   Calendar c = Calendar.getInstance();
   c.set(1986, 04, 05); // May 5, 1986
   Date d1 = c.getTime();
   // Create a Date object for today.
   Date d2 = new Date(); // today
   DateFormat df_us = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
       DateFormat.MEDIUM, l1), df_sp = DateFormat.getDateTimeInstance(
       DateFormat.MEDIUM, DateFormat.MEDIUM, l2);
   System.out.println("Date d1 for US is " + df_us.format(d1));
   System.out.println("Date d1 for Spain is " + df_sp.format(d1));
   System.out.println("Date d2 is " + df_us.format(d2));
 }

}





 </source>
   
  
 
  



Try month in a leap year

   <source lang="java">
    

import java.util.Calendar; import java.util.GregorianCalendar; public class Main {

 public static void main(String[] argv) throws Exception {
   Calendar cal = new GregorianCalendar(2000, Calendar.FEBRUARY, 1);
   int days = cal.getActualMaximum(Calendar.DAY_OF_MONTH); // 29
 }

}



 </source>
   
  
 
  



Use the SimpleDateFormat from the java.text package

   <source lang="java">
   

import java.text.SimpleDateFormat; import java.util.Calendar; public class Main {

 public static void main(String args[]) {
   String DATE_FORMAT = "yyyyMMdd";
   SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
   Calendar c1 = Calendar.getInstance(); // today
   System.out.println("Today is " + sdf.format(c1.getTime()));
 }

}



 </source>
   
  
 
  



Utilities for java.util.Date

   <source lang="java">
  

/* Dates.java

{{IS_NOTE
Purpose:
Description:
History:
2001/12/3, Henri Chen: Created.
}}IS_NOTE
Copyright (C) 2001 Potix Corporation. All Rights Reserved.
{{IS_RIGHT
This program is distributed under GPL Version 3.0 in the hope that
it will be useful, but WITHOUT ANY WARRANTY.
}}IS_RIGHT
*/

import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /**

* Utilities for java.util.Date
* 
* @author henrichen
* @author tomyeh
*/

public class Dates {

 /**
  * Truncates date to the nearest precision milliseconds. MS SQLServer2000 with
  * only the maximum accuracy of 1/300 seconds would not be able to store up to
  * one millisecond accurarcy. That is, User must round the millisecond to some
  * less precisions; or the data in that db would be inconsistence with that in
  * memory. It is useful to store a Date object in a database. Without
  * rounding, if you want to get it back and compare with the one in the
  * memory. See {@link #now} for details.
  * 
  * @param precision
  *          the divider of the precision(e.g. 10 for precision of 10
  *          milliseconds;i.e. all millisecond less than 10 would be truncated)
  * @see #now
  * @see #round(long, int)
  */
 public static final Date round(Date date, int precision) {
   date.setTime(round(date.getTime(), precision));
   return date;
 }
 /**
  * Rounds a date represented in long to the specified precision of
  * milliseconds.
  * 
  * @param time
  *          the date represented in long.
  * @param precision
  *          the divider of the precision(e.g. 10 for precision of 10
  *          milliseconds;i.e. all millisecond less than 10 would be truncated)
  * @see #now
  * @see #round(Date, int)
  */
 public static final long round(long time, int precision) {
   return time - (time % precision);
 }
 /**
  * Tests whether a date is rounded. It is mainly used for debugging.
  */
 public static final boolean isRounded(Date date, int precision) {
   return (date.getTime() % precision) == 0;
 }
 /**
  * Returns the current time but rounding to the specified precision of
  * milliseconds. It is useful if you want to create the current time which
  * will be stored in the database and want to compare it with something with
  * what you store in the database. Otherwise, that you get back the one you
  * store might be different, because the resolution of database timestamp is
  * usually less than one milisecond, e.g., MS SQL: 0.003 second.
  * 
*

* If you don"t cache it in the memory (remember entity beans always cache by * the container), you don"t need to round. If you are not sure, round it. * * @see #round(Date, int) */ public static final Date now(int precision) { return new Date(round(System.currentTimeMillis(), precision)); } /** * Returns the current time without rounding. */ public static final Date now() { return new Date(); } /** * Returns today by setting time to 0:0:0. */ public static final Date today() { return beginOfDate(new Date(), null); } /** * Given a date, return the previouse date of the given date (24 hrs before). */ final public static Date previousDate(Date when) { long time = when.getTime() - 24 * 60 * 60 * 1000; return new Date(time); } /** * Return the beginning date of this month. */ final public static Date beginOfMonth() { return beginOfMonth(new Date(), null); } /** * Given a date, a proper TimeZone, return the beginning date of the month of * the specified date and TimeZone. If TimeZone is null, meaning use default * TimeZone of the JVM. */ final public static Date beginOfMonth(Date when, TimeZone tz) { if (tz == null) tz = TimeZones.getCurrent(); final Calendar cal = Calendar.getInstance(tz); cal.setTimeInMillis(when.getTime()); // don"t call cal.setTime(Date) which // will reset the TimeZone. final int year = cal.get(Calendar.YEAR); final int month = cal.get(Calendar.MONTH); cal.clear(); cal.set(year, month, 1); return cal.getTime(); } /** * Return the ending date of this month. */ final public static Date endOfMonth() { return endOfMonth(new Date(), null); } /** * Given a date, a proper TimeZone, return the ending date of the month of the * specified date and TimeZone. If TimeZone is null, meaning use default * TimeZone of the JVM. */ final public static Date endOfMonth(Date when, TimeZone tz) { if (tz == null) tz = TimeZones.getCurrent(); final Calendar cal = Calendar.getInstance(tz); cal.setTimeInMillis(when.getTime()); // don"t call cal.setTime(Date) which // will reset the TimeZone. final int year = cal.get(Calendar.YEAR); final int month = cal.get(Calendar.MONTH); final int monthDays = cal.getActualMaximum(Calendar.DAY_OF_MONTH); cal.clear(); cal.set(year, month, monthDays + 1); cal.setTimeInMillis(cal.getTimeInMillis() - 1); return cal.getTime(); } /** * Whether the given date in the specified TimeZone is the last day of that * month. If TimeZone is null, meaning use default TimeZone of the JVM. */ final public static boolean isEndOfMonth(Date when, TimeZone tz) { if (tz == null) tz = TimeZones.getCurrent(); final Calendar cal = Calendar.getInstance(tz); cal.setTimeInMillis(when.getTime()); // don"t call cal.setTime(Date) which // will reset the TimeZone. final int day = cal.get(Calendar.DAY_OF_MONTH); final int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH); return day == maxDay; } /** * Whether the given date in the specified TimeZone is the first day of that * month. If TimeZone is null, meaning use default TimeZone of the JVM. */ final public static boolean isBeginOfMonth(Date when, TimeZone tz) { if (tz == null) tz = TimeZones.getCurrent(); final Calendar cal = Calendar.getInstance(tz); cal.setTimeInMillis(when.getTime()); // don"t call cal.setTime(Date) which // will reset the TimeZone. final int day = cal.get(Calendar.DAY_OF_MONTH); return day == 1; } /** * Given a date, a proper TimeZone, return the beginning date of the specified * date and TimeZone. If TimeZone is null, meaning use Defult TimeZone of the * JVM. */ final public static Date beginOfDate(Date when, TimeZone tz) { if (tz == null) tz = TimeZones.getCurrent(); final Calendar cal = Calendar.getInstance(tz); cal.setTimeInMillis(when.getTime());// don"t call cal.setTime(Date) which // will reset the TimeZone. final int day = cal.get(Calendar.DAY_OF_MONTH); final int year = cal.get(Calendar.YEAR); final int month = cal.get(Calendar.MONTH); cal.clear(); cal.set(year, month, day); return cal.getTime(); } /** * Given a date, a proper TimeZone, return the last millisecond date of the * specified date and TimeZone. If TimeZone is null, meaning use Defult * TimeZone of the JVM. */ final public static Date endOfDate(Date when, TimeZone tz) { if (tz == null) tz = TimeZones.getCurrent(); final Calendar cal = Calendar.getInstance(tz); cal.setTimeInMillis(when.getTime());// don"t call cal.setTime(Date) which // will reset the TimeZone. final int day = cal.get(Calendar.DAY_OF_MONTH); final int year = cal.get(Calendar.YEAR); final int month = cal.get(Calendar.MONTH); cal.clear(); cal.set(year, month, day + 1); cal.setTimeInMillis(cal.getTimeInMillis() - 1); return cal.getTime(); } /** * Return the beginning date of this year. */ final public static Date beginOfYear() { return beginOfYear(new Date(), null); } /** * Given a date, a proper TimeZone, return the beginning date of the month of * the specified date and TimeZone. If TimeZone is null, meaning use default * TimeZone of the JVM. */ final public static Date beginOfYear(Date when, TimeZone tz) { if (tz == null) tz = TimeZones.getCurrent(); final Calendar cal = Calendar.getInstance(tz); cal.setTimeInMillis(when.getTime()); // don"t call cal.setTime(Date) which // will reset the TimeZone. final int year = cal.get(Calendar.YEAR); cal.clear(); cal.set(year, Calendar.JANUARY, 1); return cal.getTime(); } /** * Return the ending date of this year. */ final public static Date endOfYear() { return endOfYear(new Date(), null); } /** * Given a date, a proper TimeZone, return the ending date of the month of the * specified date and TimeZone. If TimeZone is null, meaning use default * TimeZone of the JVM. */ final public static Date endOfYear(Date when, TimeZone tz) { if (tz == null) tz = TimeZones.getCurrent(); final Calendar cal = Calendar.getInstance(tz); cal.setTimeInMillis(when.getTime()); // don"t call cal.setTime(Date) which // will reset the TimeZone. final int year = cal.get(Calendar.YEAR); cal.clear(); cal.set(year + 1, Calendar.JANUARY, 1); cal.setTimeInMillis(cal.getTimeInMillis() - 1); return cal.getTime(); } /** * Return the ending date of this year. */ final public static short twoMonthShort() { return twoMonthShort(new Date(), null); } /** * Given a date, a proper TimeZone, return the two month int. eg. 1, 3, 5, 7, * 9, 11. If TimeZone is null, meaning use default TimeZone of the JVM. */ final public static short twoMonthShort(Date when, TimeZone tz) { if (tz == null) tz = TimeZones.getCurrent(); final Calendar cal = Calendar.getInstance(tz); cal.setTimeInMillis(when.getTime()); // don"t call cal.setTime(Date) which // will reset the TimeZone. final int month = (cal.get(Calendar.MONTH) / 2) * 2 + 1; return (short) month; } /** * Get the year of a date. * * @param when * The date. * @param tz * The time zone; if null, the current time zone is assumed. * @see #localizedYearOfDate */ public static final int yearOfDate(Date when, TimeZone tz) { if (tz == null) tz = TimeZones.getCurrent(); final Calendar cal = Calendar.getInstance(tz); cal.setTimeInMillis(when.getTime()); // don"t call cal.setTime(Date) which // will reset the TimeZone. return cal.get(Calendar.YEAR); } /** * Get the year of a date in the specified locale. * * <p> * Currenty, only Locale.ZH_TW is supported, i.e., "year - 1911" and it"s may * be less than 0. Otherwise, it is the same as {@link #yearOfDate}. * * @param when * The date. * @param locale * the locale; if null, the current locale is assumed. * @param tz * The time zone; if null, the current time zone is assumed. * @see #yearOfDate */ public static final int localizedYearOfDate(Date when, Locale locale, TimeZone tz) { final int year = yearOfDate(when, tz); if (locale.equals(Locale.TAIWAN)) return year - 1911; return year; } /** * Get the month of a date. The first month of the year is JANUARY which is 0. * * @param when * The date. * @param tz * The time zone; if null, the current time zone is assumed. */ public static final int monthOfDate(Date when, TimeZone tz) { if (tz == null) tz = TimeZones.getCurrent(); final Calendar cal = Calendar.getInstance(tz); cal.setTimeInMillis(when.getTime()); // don"t call cal.setTime(Date) which // will reset the TimeZone. return cal.get(Calendar.MONTH); } /** * Get the month of a date. The first month of the year is JANUARY which is 1. * * @param when * The date. * @param tz * The time zone; if null, the current time zone is assumed. */ public static final int monthOfDatePlus1(Date when, TimeZone tz) { if (tz == null) tz = TimeZones.getCurrent(); final Calendar cal = Calendar.getInstance(tz); cal.setTimeInMillis(when.getTime()); // don"t call cal.setTime(Date) which // will reset the TimeZone. return cal.get(Calendar.MONTH) + 1; } /** * Get the day of month of a date. The first day of the month has value 1. * * @param when * The date. * @param tz * The time zone; if null, the current time zone is assumed. */ public static final int dayMonthOfDate(Date when, TimeZone tz) { if (tz == null) tz = TimeZones.getCurrent(); final Calendar cal = Calendar.getInstance(tz); cal.setTimeInMillis(when.getTime()); // don"t call cal.setTime(Date) which // will reset the TimeZone. return cal.get(Calendar.DAY_OF_MONTH); } /** * Date Arithmetic function. Adds the specified (signed) amount of time to the * given date, based on the calendar"s rules. * * @param when * The based date. * @param tz * The time zone; if null, the current time zone is assumed. * @param field * The time field. * @param amount * The amount of date or time to be added to the field. */ public static final Date add(Date when, TimeZone tz, int field, int amount) { if (tz == null) tz = TimeZones.getCurrent(); final Calendar cal = Calendar.getInstance(tz); cal.setTimeInMillis(when.getTime());// don"t call cal.setTime(Date) which // will reset the TimeZone. cal.add(field, amount); return cal.getTime(); } /** * Date Arithmetic function (date2 - date1). subtract a date from another * date, return the difference as the required fields. E.g. if specified * Calendar.Date, the smaller range of fields is ignored and this method * return the difference of days. * * @param date2 * The date2. * @param tz * The time zone. * @param field * The time field; e.g., Calendar.DATE, Calendar.YEAR, it"s default * value is Calendar.DATE * @param date1 * The date1. */ public static final long subtract(Date date2, TimeZone tz, int field, Date date1) { if (tz == null) tz = TimeZones.getCurrent(); boolean negative = false; if (date1.after(date2)) { negative = true; final Date d = date1; date1 = date2; date2 = d; } final Calendar cal1 = Calendar.getInstance(tz); cal1.setTimeInMillis(date1.getTime());// don"t call cal.setTime(Date) which // will reset the TimeZone. final Calendar cal2 = Calendar.getInstance(tz); cal2.setTimeInMillis(date2.getTime());// don"t call cal.setTime(Date) which // will reset the TimeZone. int year1 = cal1.get(Calendar.YEAR); int year2 = cal2.get(Calendar.YEAR); switch (field) { case Calendar.YEAR: { return negative ? (year1 - year2) : (year2 - year1); } case Calendar.MONTH: { int month1 = cal1.get(Calendar.MONTH); int month2 = cal2.get(Calendar.MONTH); int months = 12 * (year2 - year1) + month2 - month1; return negative ? -months : months; } case Calendar.HOUR: { long time1 = date1.getTime(); long time2 = date2.getTime(); long min1 = (time1 < 0 ? (time1 - (1000 * 60 * 60 - 1)) : time1) / (1000 * 60 * 60); long min2 = (time2 < 0 ? (time2 - (1000 * 60 * 60 - 1)) : time2) / (1000 * 60 * 60); return negative ? (min1 - min2) : (min2 - min1); } case Calendar.MINUTE: { long time1 = date1.getTime(); long time2 = date2.getTime(); long min1 = (time1 < 0 ? (time1 - (1000 * 60 - 1)) : time1) / (1000 * 60); long min2 = (time2 < 0 ? (time2 - (1000 * 60 - 1)) : time2) / (1000 * 60); return negative ? (min1 - min2) : (min2 - min1); } case Calendar.SECOND: { long time1 = date1.getTime(); long time2 = date2.getTime(); long sec1 = (time1 < 0 ? (time1 - (1000 - 1)) : time1) / 1000; long sec2 = (time2 < 0 ? (time2 - (1000 - 1)) : time2) / 1000; return negative ? (sec1 - sec2) : (sec2 - sec1); } case Calendar.MILLISECOND: { return negative ? (date1.getTime() - date2.getTime()) : (date2.getTime() - date1.getTime()); } case Calendar.DATE: default: /* default, like -1 */ { int day1 = cal1.get(Calendar.DAY_OF_YEAR); int day2 = cal2.get(Calendar.DAY_OF_YEAR); int maxDay1 = year1 == year2 ? 0 : cal1.getActualMaximum(Calendar.DAY_OF_YEAR); int days = maxDay1 - day1 + day2; final Calendar cal = Calendar.getInstance(tz); for (int year = year1 + 1; year < year2; year++) { cal.set(Calendar.YEAR, year); days += cal.getActualMaximum(Calendar.DAY_OF_YEAR); } return negative ? -days : days; } } } /** * merge the date part and time part of two specified dates into a date. * * @param datePart * The date part date. * @param timePart * The time part date. * @param tz * The time zone. */ public static final Date merge(Date datePart, Date timePart, TimeZone tz) { if (tz == null) tz = TimeZones.getCurrent(); final Calendar dateCal = Calendar.getInstance(tz); dateCal.setTimeInMillis(datePart.getTime());// don"t call cal.setTime(Date) // which will reset the // TimeZone. final Calendar timeCal = Calendar.getInstance(tz); timeCal.setTimeInMillis(timePart.getTime());// don"t call cal.setTime(Date) // which will reset the // TimeZone. final int hour = timeCal.get(Calendar.HOUR); final int minute = timeCal.get(Calendar.MINUTE); final int second = timeCal.get(Calendar.SECOND); final int msillisecond = timeCal.get(Calendar.MILLISECOND); dateCal.set(Calendar.HOUR, hour); dateCal.set(Calendar.MINUTE, minute); dateCal.set(Calendar.SECOND, second); dateCal.set(Calendar.MILLISECOND, msillisecond); return dateCal.getTime(); } } /* * TimeZones.java * * {{IS_NOTE Purpose: * * Description: * * History: Mon Jun 12 12:17:03 2006, Created by tomyeh }}IS_NOTE * * Copyright (C) 2006 Potix Corporation. All Rights Reserved. * * Шаблон:IS RIGHTIS_RIGHT */ /** * Utilities to access time-zone. * * @author tomyeh */ class TimeZones { private static final InheritableThreadLocal _thdTZone = new InheritableThreadLocal(); /** * Returns the current time zone; never null. This is the time zone that every * other objects shall use, unless they have special consideration. * * <p> * Default: If {@link #setThreadLocal} was called with non-null, the value is * returned. Otherwise, TimeZone.getDefault() is returned, */ public static final TimeZone getCurrent() { final TimeZone l = (TimeZone) _thdTZone.get(); return l != null ? l : TimeZone.getDefault(); } /** * Sets the time-zone for the current thread only. * * <p> * Each thread could have an independent time zone, called the thread time * zone. * * <p> * When Invoking this method under a thread that serves requests, remember to * clean up the setting upon completing each request. * *

<code>
   * TimeZone old = TimeZones.setThreadLocal(newValue);
   * try { 
   *   ...
   * } finally {
   *   TimeZones.setThreadLocal(old);
   * }
   * </code>
  * 
  * @param timezone
  *          the thread time zone; null to denote no thread time zone (and the
  *          system"s timezone will be used instead)
  * @return the previous thread time zone, or null if no previous time zone
  */
 public static final TimeZone setThreadLocal(TimeZone timezone) {
   final TimeZone old = (TimeZone) _thdTZone.get();
   _thdTZone.set(timezone);
   return old;
 }
 /**
  * Returns the time zone defined by {@link #setThreadLocal}.
  * 
  * @since 3.0.0
  * @see #getCurrent
  */
 public static final TimeZone getThreadLocal() {
   return (TimeZone) _thdTZone.get();
 }
 /**
  * Returns the time by specifying the offset in minutes.
  * 
  * <p>
  * For example, the following are equivalent.
  * 
*
<code>
   * TimeZone.getTimeZone("GMT+8");
   * TimeZones.getTimeZone(480);
   * </code>
  * 
  * @param ofsmins
  *          the offset in minutes.
  */
 public static final TimeZone getTimeZone(int ofsmins) {
   final StringBuffer sb = new StringBuffer(8).append("GMT");
   if (ofsmins >= 0) {
     sb.append("+");
   } else {
     sb.append("-");
     ofsmins = -ofsmins;
   }
   final int hr = ofsmins / 60, min = ofsmins % 60;
   if (min == 0) {
     sb.append(hr);
   } else {
     if (hr < 10)
       sb.append("0");
     sb.append(hr).append(":");
     if (min < 10)
       sb.append("0");
     sb.append(min);
   }
   return TimeZone.getTimeZone(sb.toString());
 }

}


 </source>
   
  
 
  



Validate a date Using DateFormat

   <source lang="java">
   

import java.text.DateFormat; public class Main {

 public static boolean isValidDateStr(String date) throws Exception {
   DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
   df.setLenient(false);
   df.parse(date);
   return true;
 }
 public static void main(String[] args) throws Exception{
   System.out.println(isValidDateStr("1900-13-12"));
 }

}



 </source>
   
  
 
  



When does the UNIX date get into trouble

   <source lang="java">
    

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

/** When does the UNIX date get into trouble? */ public class Y2038 {

 public static void main(String[] a) {
   // This should yield 2038AD, the hour of doom for the
   // last remaining 32-bit UNIX systems (there will be
   // millions of 64-bit UNIXes by then).
   long expiry = 0x7FFFFFFFL;
   System.out.println("32-bit UNIX expires on " + Long.toHexString(expiry)
       + " or " + new java.util.Date(expiry * 1000));
 }

}




 </source>