Java/Data Type/Date Calculation

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

Содержание

Adds a number of days to a date returning a new object.

   <source lang="java">
 

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 {

 //-----------------------------------------------------------------------
 /**
  * Adds a number of days to a date returning a new object.
  * The original date object is unchanged.
  *
  * @param date  the date, not null
  * @param amount  the amount to add, may be negative
  * @return the new date object with the amount added
  * @throws IllegalArgumentException if the date is null
  */
 public static Date addDays(Date date, int amount) {
     return add(date, Calendar.DAY_OF_MONTH, amount);
 }
 //-----------------------------------------------------------------------
 /**
  * Adds to a date returning a new object.
  * The original date object is unchanged.
  *
  * @param date  the date, not null
  * @param calendarField  the calendar field to add to
  * @param amount  the amount to add, may be negative
  * @return the new date object with the amount added
  * @throws IllegalArgumentException if the date is null
  */
 private static Date add(Date date, int calendarField, int amount) {
     if (date == null) {
         throw new IllegalArgumentException("The date must not be null");
     }
     Calendar c = Calendar.getInstance();
     c.setTime(date);
     c.add(calendarField, amount);
     return c.getTime();
 }

}


 </source>
   
  
 
  



Adds a number of hours to a date returning a new object.

   <source lang="java">
 

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 {

 //-----------------------------------------------------------------------
 /**
  * Adds a number of hours to a date returning a new object.
  * The original date object is unchanged.
  *
  * @param date  the date, not null
  * @param amount  the amount to add, may be negative
  * @return the new date object with the amount added
  * @throws IllegalArgumentException if the date is null
  */
 public static Date addHours(Date date, int amount) {
     return add(date, Calendar.HOUR_OF_DAY, amount);
 }
 //-----------------------------------------------------------------------
 /**
  * Adds to a date returning a new object.
  * The original date object is unchanged.
  *
  * @param date  the date, not null
  * @param calendarField  the calendar field to add to
  * @param amount  the amount to add, may be negative
  * @return the new date object with the amount added
  * @throws IllegalArgumentException if the date is null
  */
 private static Date add(Date date, int calendarField, int amount) {
     if (date == null) {
         throw new IllegalArgumentException("The date must not be null");
     }
     Calendar c = Calendar.getInstance();
     c.setTime(date);
     c.add(calendarField, amount);
     return c.getTime();
 }

}


 </source>
   
  
 
  



Adds a number of milliseconds to a date returning a new object.

   <source lang="java">
 

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 {

 //-----------------------------------------------------------------------
 /**
  * Adds a number of milliseconds to a date returning a new object.
  * The original date object is unchanged.
  *
  * @param date  the date, not null
  * @param amount  the amount to add, may be negative
  * @return the new date object with the amount added
  * @throws IllegalArgumentException if the date is null
  */
 public static Date addMilliseconds(Date date, int amount) {
     return add(date, Calendar.MILLISECOND, amount);
 }
 //-----------------------------------------------------------------------
 /**
  * Adds to a date returning a new object.
  * The original date object is unchanged.
  *
  * @param date  the date, not null
  * @param calendarField  the calendar field to add to
  * @param amount  the amount to add, may be negative
  * @return the new date object with the amount added
  * @throws IllegalArgumentException if the date is null
  */
 private static Date add(Date date, int calendarField, int amount) {
     if (date == null) {
         throw new IllegalArgumentException("The date must not be null");
     }
     Calendar c = Calendar.getInstance();
     c.setTime(date);
     c.add(calendarField, amount);
     return c.getTime();
 }

}


 </source>
   
  
 
  



Adds a number of minutes to a date returning a new object.

   <source lang="java">
 

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 {

 //-----------------------------------------------------------------------
 /**
  * Adds a number of minutes to a date returning a new object.
  * The original date object is unchanged.
  *
  * @param date  the date, not null
  * @param amount  the amount to add, may be negative
  * @return the new date object with the amount added
  * @throws IllegalArgumentException if the date is null
  */
 public static Date addMinutes(Date date, int amount) {
     return add(date, Calendar.MINUTE, amount);
 }
 //-----------------------------------------------------------------------
 /**
  * Adds to a date returning a new object.
  * The original date object is unchanged.
  *
  * @param date  the date, not null
  * @param calendarField  the calendar field to add to
  * @param amount  the amount to add, may be negative
  * @return the new date object with the amount added
  * @throws IllegalArgumentException if the date is null
  */
 private static Date add(Date date, int calendarField, int amount) {
     if (date == null) {
         throw new IllegalArgumentException("The date must not be null");
     }
     Calendar c = Calendar.getInstance();
     c.setTime(date);
     c.add(calendarField, amount);
     return c.getTime();
 }

}


 </source>
   
  
 
  



Adds a number of months to a date returning a new object.

   <source lang="java">
 

import java.math.BigDecimal; import java.math.BigInteger; import java.text.ParseException; import java.text.ParsePosition; import java.text.SimpleDateFormat; 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 {

 //-----------------------------------------------------------------------
 /**
  * Adds a number of months to a date returning a new object.
  * The original date object is unchanged.
  *
  * @param date  the date, not null
  * @param amount  the amount to add, may be negative
  * @return the new date object with the amount added
  * @throws IllegalArgumentException if the date is null
  */
 public static Date addMonths(Date date, int amount) {
     return add(date, Calendar.MONTH, amount);
 }
 //-----------------------------------------------------------------------
 /**
  * Adds to a date returning a new object.
  * The original date object is unchanged.
  *
  * @param date  the date, not null
  * @param calendarField  the calendar field to add to
  * @param amount  the amount to add, may be negative
  * @return the new date object with the amount added
  * @throws IllegalArgumentException if the date is null
  */
 private static Date add(Date date, int calendarField, int amount) {
     if (date == null) {
         throw new IllegalArgumentException("The date must not be null");
     }
     Calendar c = Calendar.getInstance();
     c.setTime(date);
     c.add(calendarField, amount);
     return c.getTime();
 }

}


 </source>
   
  
 
  



Adds a number of seconds to a date returning a new object.

   <source lang="java">
 

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 {

 //-----------------------------------------------------------------------
 /**
  * Adds a number of seconds to a date returning a new object.
  * The original date object is unchanged.
  *
  * @param date  the date, not null
  * @param amount  the amount to add, may be negative
  * @return the new date object with the amount added
  * @throws IllegalArgumentException if the date is null
  */
 public static Date addSeconds(Date date, int amount) {
     return add(date, Calendar.SECOND, amount);
 }
 //-----------------------------------------------------------------------
 /**
  * Adds to a date returning a new object.
  * The original date object is unchanged.
  *
  * @param date  the date, not null
  * @param calendarField  the calendar field to add to
  * @param amount  the amount to add, may be negative
  * @return the new date object with the amount added
  * @throws IllegalArgumentException if the date is null
  */
 private static Date add(Date date, int calendarField, int amount) {
     if (date == null) {
         throw new IllegalArgumentException("The date must not be null");
     }
     Calendar c = Calendar.getInstance();
     c.setTime(date);
     c.add(calendarField, amount);
     return c.getTime();
 }

}


 </source>
   
  
 
  



Adds a number of weeks to a date returning a new object.

   <source lang="java">
 

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 {

 //-----------------------------------------------------------------------
 /**
  * Adds a number of weeks to a date returning a new object.
  * The original date object is unchanged.
  *
  * @param date  the date, not null
  * @param amount  the amount to add, may be negative
  * @return the new date object with the amount added
  * @throws IllegalArgumentException if the date is null
  */
 public static Date addWeeks(Date date, int amount) {
     return add(date, Calendar.WEEK_OF_YEAR, amount);
 }
 //-----------------------------------------------------------------------
 /**
  * Adds to a date returning a new object.
  * The original date object is unchanged.
  *
  * @param date  the date, not null
  * @param calendarField  the calendar field to add to
  * @param amount  the amount to add, may be negative
  * @return the new date object with the amount added
  * @throws IllegalArgumentException if the date is null
  */
 private static Date add(Date date, int calendarField, int amount) {
     if (date == null) {
         throw new IllegalArgumentException("The date must not be null");
     }
     Calendar c = Calendar.getInstance();
     c.setTime(date);
     c.add(calendarField, amount);
     return c.getTime();
 }

}


 </source>
   
  
 
  



Adds a number of years to a date returning a new object.

   <source lang="java">
 

import java.math.BigDecimal; import java.math.BigInteger; import java.text.ParseException; import java.text.ParsePosition; import java.text.SimpleDateFormat; 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 {

 //-----------------------------------------------------------------------
 /**
  * Adds a number of years to a date returning a new object.
  * The original date object is unchanged.
  *
  * @param date  the date, not null
  * @param amount  the amount to add, may be negative
  * @return the new date object with the amount added
  * @throws IllegalArgumentException if the date is null
  */
 public static Date addYears(Date date, int amount) {
     return add(date, Calendar.YEAR, amount);
 }
 //-----------------------------------------------------------------------
 /**
  * Adds to a date returning a new object.
  * The original date object is unchanged.
  *
  * @param date  the date, not null
  * @param calendarField  the calendar field to add to
  * @param amount  the amount to add, may be negative
  * @return the new date object with the amount added
  * @throws IllegalArgumentException if the date is null
  */
 private static Date add(Date date, int calendarField, int amount) {
     if (date == null) {
         throw new IllegalArgumentException("The date must not be null");
     }
     Calendar c = Calendar.getInstance();
     c.setTime(date);
     c.add(calendarField, amount);
     return c.getTime();
 }

}


 </source>
   
  
 
  



Calculate Holidays

   <source lang="java">
 

//** Copyright Statement *************************************************** //The Salmon Open Framework for Internet Applications (SOFIA) // Copyright (C) 1999 - 2002, Salmon LLC // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License version 2 // 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // For more information please visit http://www.salmonllc.ru //** End Copyright Statement *************************************************** // // // Author: Gregory N. Mirsky // Updated: John D. Mitchell // Version 1.02 //

import java.util.Calendar;

public class Holidays

   {

//********************************* // Miscellaneous other holidays are left as an exercise for the reader. // // public static Date QuebecCivicHoliday (int nYear) // { // // 03 January YYYY // } // // public static Date AshWednesday (int nYear) // { // // 42 days before easter... // } // // public static Date PalmSunday (int nYear) // { // // Sunday before Easter Sunday... // } // // public static Date MaundayThursday (int nYear) // { // // Thursday before Easter... // } // // public static Date RoshHashanah(int nYear) // { // Source: William H. Jefferys, Department of Astronomy, University of // Texas Austin, TX 78712 // // http://quasar.as.utexas.edu // // First, calculate the Golden Number G. This is fundamental to the // calculation of both the date of Easter and the Date of Rosh Hashanah. // It is intimately connected with the Metonic Cycle. For any year Y, the // Golden Number is defined as // // G = Remainder(Y|19) + 1. Don"t forget to add the 1!!! // // The following rules are also due to John Horton Conway, of Princeton // University. In the Gregorian year Y of the Common Era, Rosh Hashanah // normally falls on September N, where // // N + fraction = {[Y/100] - [Y/400] - 2} + // 765433/492480*Remainder(12G|19) + Remainder(Y|4)/4 - (313Y+89081)/98496 // // Here, G is the Golden Number, and * means multiply. However, if certain // conditions are satisfied, Rosh Hashanah is postponed by one or even two // days, as follows: // // ***Postponement rules*** // // 1.If the day calculated above is a Sunday, Wednesday, or Friday, Rosh // Hashanah falls on the next day (Monday, Thursday or Saturday, // respectively). // // 2.If the calculated day is a Monday, and if the fraction is greater // than or equal to 23269/25920, and if Remainder(12G|19) is greater than // 11, Rosh Hashanah falls on the next day, a Tuesday. // // 3.If it is a Tuesday, and if the fraction is greater than or equal to // 1367/2160, and if Remainder(12G|19) is greater than 6, Rosh Hashanah // falls two days later, on Thursday (NOT WEDNESDAY!!). // } // // public static Date Passover(int nYear) // { // Source: William H. Jefferys, Department of Astronomy, University of // Texas Austin, TX 78712 // // http://quasar.as.utexas.edu // // Once you have determined the date of Rosh Hashanah, it is easy to // calculate the date of Passover in the same (Gregorian or Julian) // year. Let M = the number of days from September 6 to Rosh Hashanah. // In the example for 1996, M=September 14-September 6 = 8 days. // // Count M days from March 27. That is the date of Passover. It actually // begins at sundown on the previous evening. In the example for 1996, 8 // days after March 27 is April 4 (there are 31 days in March), so // Passover begins at sundown on April 3. // } // // public static Date DominionDay (int nYear) // { // // 01 July YYYY // } // // public static Date BoxingDay (int nYear) // { // // Day after Christmas, December 26th... // } // //*********************************************


public static java.util.Calendar AbrahamLincolnsBirthday (int nYear){

 int nMonth = 1; // February
 // February 12th
 java.util.Calendar cal = java.util.Calendar.getInstance();
 cal.set(nYear, nMonth, 12); 
 return cal;

} public static java.util.Calendar ChristmasDay (int nYear){

 int nMonth = 11; // Decmeber
 // December 25th
 java.util.Calendar cal = java.util.Calendar.getInstance();
 cal.set(nYear, nMonth, 25);
 return cal;

}

   public static java.util.Calendar ChristmasDayObserved (int nYear)
 {
 int nX;
 int nMonth = 11; // December
 java.util.Calendar cal;
 cal = java.util.Calendar.getInstance();
 cal.set(nYear, nMonth, 25);
 nX = cal.get(Calendar.DAY_OF_WEEK);
 switch(nX)
     {
     case 0 : {// Sunday
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 26);
     return cal;
     }
     case 1 : // Monday
     case 2 : // Tuesday
     case 3 : // Wednesday
     case 4 : // Thrusday
     case 5 :{ // Friday
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 25);
     return cal;
     }
     default :{
   // Saturday
     cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 24);
     return cal;
     }
   }

}

   public static java.util.Calendar ColumbusDayObserved (int nYear)
 {
 // Second Monday in October
 int nX;
 int nMonth = 9; // October 
 java.util.Calendar cal;
 cal = java.util.Calendar.getInstance();
 cal.set(nYear, nMonth, 1);
 nX = cal.get(Calendar.DAY_OF_WEEK);
 switch(nX)
     {
     case 0 : {// Sunday
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 9);
     return cal;
     }
   case 1 : {// Monday
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 15);
     return cal;
     }
     case 2 : // Tuesday
     {
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 14);
     return cal;
     }
     case 3 : // Wednesday
   {
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 13);
     return cal;
     }
     case 4 : // Thrusday
   {
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 12);
     return cal;
     }
     case 5 : // Friday
   {
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 11);
     return cal;
     }
     default : // Saturday
   {
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 10);
     return cal;
     }
     }
 }
   public static java.util.Calendar EasterMonday (int nYear)
 {
 int nEasterMonth = 0;
 int nEasterDay   = 0;
 int nMonthMarch  = 2; // March
 int nMonthApril  = 3; // April
 java.util.Calendar cEasterSunday = EasterSunday(nYear);
 nEasterMonth = cEasterSunday.get(Calendar.MONTH);
 nEasterDay = cEasterSunday.get(Calendar.DAY_OF_MONTH);
 if (nEasterMonth == nMonthMarch || nEasterDay == 31){
   java.util.Calendar cal = java.util.Calendar.getInstance();
   cal.set(nYear, nMonthApril, 1);
   return cal;
 }else{
   java.util.Calendar cal = java.util.Calendar.getInstance();
   cal.set(nYear, nEasterMonth, ++nEasterDay);
   return cal;
 }

}

   public static java.util.Calendar EasterSunday(int nYear)
 { 

/* Calculate Easter Sunday

 Written by Gregory N. Mirsky
 Source: 2nd Edition by Peter Duffett-Smith. It was originally from
 Butcher"s Ecclesiastical Calendar, published in 1876. This
 algorithm has also been published in the 1922 book General
 Astronomy by Spencer Jones; in The Journal of the British
 Astronomical Association (Vol.88, page 91, December 1977); and in
 Astronomical Algorithms (1991) by Jean Meeus.
 This algorithm holds for any year in the Gregorian Calendar, which
 (of course) means years including and after 1583.
       a=year%19
       b=year/100
       c=year%100
       d=b/4
       e=b%4
       f=(b+8)/25
       g=(b-f+1)/3
       h=(19*a+b-d-g+15)%30
       i=c/4
       k=c%4
       l=(32+2*e+2*i-h-k)%7
       m=(a+11*h+22*l)/451
       Easter Month =(h+l-7*m+114)/31  [3=March, 4=April]
       p=(h+l-7*m+114)%31
       Easter Date=p+1     (date in Easter Month)
 Note: Integer truncation is already factored into the
 calculations. Using higher percision variables will cause
 inaccurate calculations. 
  • /
 int nA      = 0;
 int nB      = 0;
 int nC      = 0;  
 int nD      = 0;
 int nE      = 0;
 int nF      = 0;
 int nG      = 0;
 int nH      = 0;
 int nI      = 0;
 int nK      = 0;
 int nL      = 0;
 int nM      = 0;
 int nP      = 0;
 int nEasterMonth  = 0;
 int nEasterDay    = 0;
 // Calculate Easter
 if (nYear < 1900) 
     { 
     // if year is in java format put it into standard
     // format for the calculation
     nYear += 1900; 
     }
 nA = nYear % 19;
 nB = nYear / 100;
 nC = nYear % 100;
 nD = nB / 4;
 nE = nB % 4;
 nF = (nB + 8) / 25;
 nG = (nB - nF + 1) / 3;
 nH = (19 * nA + nB - nD - nG + 15) % 30;
 nI = nC / 4;
 nK = nC % 4;
 nL = (32 + 2 * nE + 2 * nI - nH - nK) % 7;
 nM=  (nA + 11 * nH + 22 * nL) / 451;
 //  [3=March, 4=April]
 nEasterMonth = (nH + nL - 7 * nM + 114) / 31;
 --nEasterMonth;
 nP = (nH + nL - 7 * nM + 114) % 31;
 // Date in Easter Month.
 nEasterDay = nP + 1;
 // Uncorrect for our earlier correction.
 nYear -= 1900;
 // Populate the date object...
 java.util.Calendar cal = java.util.Calendar.getInstance();
 cal.set(nYear, nEasterMonth, nEasterDay);
 return cal;
 }
   public static java.util.Calendar GoodFridayObserved(int nYear)
 {
 // Get Easter Sunday and subtract two days
 int nEasterMonth  = 0;
 int nEasterDay    = 0;
 int nGoodFridayMonth  = 0;
 int nGoodFridayDay  = 0;
 java.util.Calendar cEasterSunday;
   
 cEasterSunday = EasterSunday(nYear);
 nEasterMonth = cEasterSunday.get(Calendar.MONTH);
 nEasterDay = cEasterSunday.get(Calendar.DAY_OF_MONTH);
 if (nEasterDay <= 3 && nEasterMonth == 3){ // Check if <= April 3rd
     
     switch(nEasterDay){
   case 3 : 
       nGoodFridayMonth = nEasterMonth - 1;
       nGoodFridayDay   = nEasterDay - 2;
       break;
   case 2 :
       nGoodFridayMonth = nEasterMonth - 1;
       nGoodFridayDay   = 31;
       break;
   case 1 :
       nGoodFridayMonth = nEasterMonth - 1;
       nGoodFridayDay   = 31;
       break;
   default:
       nGoodFridayMonth = nEasterMonth;
       nGoodFridayDay   = nEasterDay - 2;
   }
 }else{
     nGoodFridayMonth = nEasterMonth;
     nGoodFridayDay   = nEasterDay - 2;
 }
   java.util.Calendar cal = java.util.Calendar.getInstance();
 cal.set(nYear, nGoodFridayMonth, nGoodFridayDay);
 return cal;

} public static java.util.Calendar Halloween (int nYear){

 int nMonth = 9;
 // October 31st
 java.util.Calendar cal = java.util.Calendar.getInstance();
 cal.set(nYear, nMonth, 31);
 return cal;

}

   public static java.util.Calendar IndependenceDay (int nYear)
 {
 int nMonth = 6; // July
 // July 4th
 java.util.Calendar cal = java.util.Calendar.getInstance();
 cal.set(nYear, nMonth, 4);
 return cal;

} public static java.util.Calendar IndependenceDayObserved (int nYear){

 int nX;
 int nMonth = 6; // July
 
 java.util.Calendar cal = java.util.Calendar.getInstance();
 cal.set(nYear, nMonth, 4);
     
 nX = cal.get(Calendar.DAY_OF_WEEK);
 switch(nX){
     case 0 : // Sunday
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 5);
     return cal;
   case 1 : // Monday
     case 2 : // Tuesday
     case 3 : // Wednesday
     case 4 : // Thrusday
     case 5 : // Friday
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 4);
     return cal;
     default :
   // Saturday
     cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 3);
     return cal;
   }

} public static java.util.Calendar LaborDayObserved (int nYear){

 // The first Monday in September
 int nX;
 int nMonth = 8; // September
 java.util.Calendar cal = java.util.Calendar.getInstance();
 cal.set(nYear, 9, 1);
     
 nX = cal.get(Calendar.DAY_OF_WEEK);
   
 switch(nX){
     case 0 : // Sunday
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 2);
     return cal;
   case 1 : // Monday
     cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 7);
     return cal;
     case 2 : // Tuesday
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 6);
     return cal;
     case 3 : // Wednesday
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 5);
     return cal;
     case 4 : // Thrusday
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 4);
     return cal;
     case 5 : // Friday
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 3);
     return cal;
     default : // Saturday
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 2);
     return cal;
   }

} public java.util.Calendar MartinLutherKingObserved (int nYear){

 // Third Monday in January
 int nX;
 int nMonth = 0; // January
 java.util.Calendar cal;
 cal = java.util.Calendar.getInstance();
 cal.set(nYear, nMonth, 1);
 nX = cal.get(Calendar.DAY_OF_WEEK);
 
 switch(nX) {
   case 0 : {// Sunday
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 16);
     return cal;
     }
   case 1 : {// Monday
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 15);
     return cal;
     }
     case 2 : // Tuesday
     {
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 21);
     return cal;
     }
     case 3 : // Wednesday
   {
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 20);
     return cal;
     }
     case 4 : // Thrusday
   {
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 19);
     return cal;
     }
     case 5 : // Friday
   {
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 18);
     return cal;
     }
     default : // Saturday
   {
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 17);
     return cal;
     }
     
   }

} public static java.util.Calendar MemorialDayObserved (int nYear){

 // Last Monday in May
 int nX;
 int nMonth = 4; //May
 java.util.Calendar cal = java.util.Calendar.getInstance();
 cal.set(nYear, nMonth, 31);
     
 nX = cal.get(Calendar.DAY_OF_WEEK);
 
 
 switch(nX){
    case 0 : // Sunday
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 25);
     return cal;
   case 1 : // Monday
     cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 31);
     return cal;
     case 2 : // Tuesday
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 30);
     return cal;
     case 3 : // Wednesday
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 29);
     return cal;
     case 4 : // Thrusday
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 28);
     return cal;
     case 5 : // Friday
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 27);
     return cal;
     default : // Saturday
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 26);
     return cal;
   
   }

} public static java.util.Calendar NewYearsDay (int nYear){

 // January 1st
 int nMonth = 0; // January
 java.util.Calendar cal = java.util.Calendar.getInstance();
 cal.set(nYear, nMonth, 1);
 
 return cal;

} public static java.util.Calendar NewYearsDayObserved (int nYear){

 int nX;
 int nMonth = 0;     // January
 int nMonthDecember = 11;  // December
 
 java.util.Calendar cal = java.util.Calendar.getInstance();
 cal.set(nYear, nMonth, 1);
     
 nX = cal.get(Calendar.DAY_OF_WEEK);
   
 if (nYear > 1900)
     nYear -= 1900;
 switch(nX){
     case 0 : // Sunday
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 2);
     return cal;
     case 1 : // Monday
     case 2 : // Tuesday
     case 3 : // Wednesday
     case 4 : // Thrusday
     case 5 : // Friday
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 1);
     return cal;
     default :
   // Saturday, then observe on friday of previous year
     cal = java.util.Calendar.getInstance();
     cal.set(--nYear, nMonthDecember, 31);
     return cal;
   }

} public static java.util.Calendar PresidentsDayObserved (int nYear){

 // Third Monday in February
 int nX;
 int nMonth = 1; // February
 java.util.Calendar cal = java.util.Calendar.getInstance();
 cal.set(nYear, nMonth, 1);
     
 nX = cal.get(Calendar.DAY_OF_WEEK);
 
 switch(nX){
    case 0 : {// Sunday
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 16);
     return cal;
     }
   case 1 : {// Monday
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 15);
     return cal;
     }
     case 2 : // Tuesday
     {
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 21);
     return cal;
     }
     case 3 : // Wednesday
   {
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 20);
     return cal;
     }
     case 4 : // Thrusday
   {
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 19);
     return cal;
     }
     case 5 : // Friday
   {
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 18);
     return cal;
     }
     default : // Saturday
   {
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 17);
     return cal;
     }
   }

} public static java.util.Calendar ThanksgivingObserved(int nYear){

 int nX;
 int nMonth = 10; // November
 java.util.Calendar cal = java.util.Calendar.getInstance();
 cal.set(nYear, nMonth, 1);
     
 nX = cal.get(Calendar.DAY_OF_WEEK);
 switch(nX){
   
   case 0 : {// Sunday
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 26);
     return cal;
     }
   case 1 : {// Monday
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 25);
     return cal;
     }
     case 2 : // Tuesday
     {
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 24);
     return cal;
     }
     case 3 : // Wednesday
   {
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 23);
     return cal;
     }
     case 4 : // Thrusday
   {
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 22);
     return cal;
     }
     case 5 : // Friday
   {
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 28);
     return cal;
     }
     default : // Saturday
   {
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 27);
     return cal;
     }
   }

} public static java.util.Calendar USElectionDay (int nYear){

 // First Tuesday in November
 int nX; 
 int nMonth = 10; // November
 java.util.Calendar cal = java.util.Calendar.getInstance();
 cal.set(nYear, nMonth, 1);
 nX = cal.get(Calendar.DAY_OF_WEEK);
 switch(nX){
     case 0 : {// Sunday
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 3);
     return cal;
     }
   case 1 : {// Monday
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 2);
     return cal;
     }
     case 2 : // Tuesday
     {
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 1);
     return cal;
     }
     case 3 : // Wednesday
   {
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 7);
     return cal;
     }
     case 4 : // Thrusday
   {
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 6);
     return cal;
     }
     case 5 : // Friday
   {
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 5);
     return cal;
     }
     default : // Saturday
   {
       cal = java.util.Calendar.getInstance();
     cal.set(nYear, nMonth, 4);
     return cal;
     }
   }

} public static java.util.Calendar ValentinesDay (int nYear){

 int nMonth = 1; // February
 // February 14th
 java.util.Calendar cal = java.util.Calendar.getInstance();
 cal.set(nYear, nMonth, 14);
 return cal;

} public static java.util.Calendar VeteransDayObserved (int nYear){

 //November 11th
 int nMonth = 10; // November
 java.util.Calendar cal = java.util.Calendar.getInstance();
 cal.set(nYear, nMonth, 11);
 return cal;

} public static String getClassInfo()

 {
 return ("Name: Holidays\r\n" +
   "Author: Gregory N. Mirsky\r\n" +
   "Updated: John D. Mitchell\r\n" +
   "Version 1.02\r\n" +
   "Copyright 1997, All rights reserved.");
 }

}


 </source>
   
  
 
  



Checking date as String formatted by a date format

   <source lang="java">
  

import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /**

* Utility for checking date as String formatted by a date format.
* By default, the date format u
*
* @see java.text.DateFormat
*/

public class DateUtils {

 public static final SimpleDateFormat DEFAULT_DATE_FORMAT = new SimpleDateFormat("yyyy.MM.dd HH:mm");
 private static DateFormat dateFormat = DEFAULT_DATE_FORMAT;
 private DateUtils() {
   // Instanceless class
 }
 /**
  * Returns the date from the given value parsed by the date format.
  */
 public static Date getDate(String yyyyMMdd) throws ParseException {
   synchronized (dateFormat) {
     return dateFormat.parse(yyyyMMdd);
   }
 }
 /**
  * Returns the Date as String formated by the date format.
  */
 public static String getStandardDate(Date date) {
   synchronized (dateFormat) {
     return dateFormat.format(date);
   }
 }
 /**
  * Sets the date format.
  */
 public static void setDateFormat(DateFormat dateFormat) {
   DateUtils.dateFormat = dateFormat;
 }

}


 </source>
   
  
 
  



Checks if a calendar date is after today and within a number of days in the future

   <source lang="java">
  

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

   /**
*

Checks if two dates are on the same day ignoring time.

    * @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
    */
   public static boolean isSameDay(Date date1, Date date2) {
       if (date1 == null || date2 == null) {
           throw new IllegalArgumentException("The dates 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 calendars represent the same day ignoring time.

    * @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
    */
   public static boolean isSameDay(Calendar cal1, Calendar cal2) {
       if (cal1 == null || cal2 == null) {
           throw new IllegalArgumentException("The dates 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));
   }
   
   /**
*

Checks if a date is today.

    * @param date the date, not altered, not null.
    * @return true if the date is today.
    * @throws IllegalArgumentException if the date is null
    */
   public static boolean isToday(Date date) {
       return isSameDay(date, Calendar.getInstance().getTime());
   }
   
   /**
*

Checks if a calendar date is today.

    * @param cal  the calendar, not altered, not null
    * @return true if cal date is today
    * @throws IllegalArgumentException if the calendar is null
    */
   public static boolean isToday(Calendar cal) {
       return isSameDay(cal, Calendar.getInstance());
   }
   
   /**
*

Checks if the first date is before the second date ignoring time.

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

Checks if the first calendar date is before the second calendar date ignoring time.

    * @param cal1 the first calendar, not altered, not null.
    * @param cal2 the second calendar, not altered, not null.
    * @return true if cal1 date is before cal2 date ignoring time.
    * @throws IllegalArgumentException if either of the calendars are null
    */
   public static boolean isBeforeDay(Calendar cal1, Calendar cal2) {
       if (cal1 == null || cal2 == null) {
           throw new IllegalArgumentException("The dates must not be null");
       }
       if (cal1.get(Calendar.ERA) < cal2.get(Calendar.ERA)) return true;
       if (cal1.get(Calendar.ERA) > cal2.get(Calendar.ERA)) return false;
       if (cal1.get(Calendar.YEAR) < cal2.get(Calendar.YEAR)) return true;
       if (cal1.get(Calendar.YEAR) > cal2.get(Calendar.YEAR)) return false;
       return cal1.get(Calendar.DAY_OF_YEAR) < cal2.get(Calendar.DAY_OF_YEAR);
   }
   
   /**
*

Checks if the first date is after the second date ignoring time.

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

Checks if the first calendar date is after the second calendar date ignoring time.

    * @param cal1 the first calendar, not altered, not null.
    * @param cal2 the second calendar, not altered, not null.
    * @return true if cal1 date is after cal2 date ignoring time.
    * @throws IllegalArgumentException if either of the calendars are null
    */
   public static boolean isAfterDay(Calendar cal1, Calendar cal2) {
       if (cal1 == null || cal2 == null) {
           throw new IllegalArgumentException("The dates must not be null");
       }
       if (cal1.get(Calendar.ERA) < cal2.get(Calendar.ERA)) return false;
       if (cal1.get(Calendar.ERA) > cal2.get(Calendar.ERA)) return true;
       if (cal1.get(Calendar.YEAR) < cal2.get(Calendar.YEAR)) return false;
       if (cal1.get(Calendar.YEAR) > cal2.get(Calendar.YEAR)) return true;
       return cal1.get(Calendar.DAY_OF_YEAR) > cal2.get(Calendar.DAY_OF_YEAR);
   }
   
   /**
*

Checks if a date is after today and within a number of days in the future.

    * @param date the date to check, not altered, not null.
    * @param days the number of days.
    * @return true if the date day is after today and within days in the future .
    * @throws IllegalArgumentException if the date is null
    */
   public static boolean isWithinDaysFuture(Date date, int days) {
       if (date == null) {
           throw new IllegalArgumentException("The date must not be null");
       }
       Calendar cal = Calendar.getInstance();
       cal.setTime(date);
       return isWithinDaysFuture(cal, days);
   }
   
   /**
*

Checks if a calendar date is after today and within a number of days in the future.

    * @param cal the calendar, not altered, not null
    * @param days the number of days.
    * @return true if the calendar date day is after today and within days in the future .
    * @throws IllegalArgumentException if the calendar is null
    */
   public static boolean isWithinDaysFuture(Calendar cal, int days) {
       if (cal == null) {
           throw new IllegalArgumentException("The date must not be null");
       }
       Calendar today = Calendar.getInstance();
       Calendar future = Calendar.getInstance();
       future.add(Calendar.DAY_OF_YEAR, days);
       return (isAfterDay(cal, today) && ! isAfterDay(cal, future));
   }
   
   /** Returns the given date with the time set to the start of the day. */
   public static Date getStart(Date date) {
       return clearTime(date);
   }
   
   /** Returns the given date with the time values cleared. */
   public static Date clearTime(Date date) {
       if (date == null) {
           return null;
       }
       Calendar c = Calendar.getInstance();
       c.setTime(date);
       c.set(Calendar.HOUR_OF_DAY, 0);
       c.set(Calendar.MINUTE, 0);
       c.set(Calendar.SECOND, 0);
       c.set(Calendar.MILLISECOND, 0);
       return c.getTime();
   }    
   /** Determines whether or not a date has any time values (hour, minute, 
    * seconds or millisecondsReturns the given date with the time values cleared. */
   /**
    * Determines whether or not a date has any time values.
    * @param date The date.
    * @return true iff the date is not null and any of the date"s hour, minute,
    * seconds or millisecond values are greater than zero.
    */
   public static boolean hasTime(Date date) {
       if (date == null) {
           return false;
       }
       Calendar c = Calendar.getInstance();
       c.setTime(date);
       if (c.get(Calendar.HOUR_OF_DAY) > 0) {
           return true;
       }
       if (c.get(Calendar.MINUTE) > 0) {
           return true;
       }
       if (c.get(Calendar.SECOND) > 0) {
           return true;
       }
       if (c.get(Calendar.MILLISECOND) > 0) {
           return true;
       }
       return false;
   }
   /** Returns the given date with time set to the end of the day */
   public static Date getEnd(Date date) {
       if (date == null) {
           return null;
       }
       Calendar c = Calendar.getInstance();
       c.setTime(date);
       c.set(Calendar.HOUR_OF_DAY, 23);
       c.set(Calendar.MINUTE, 59);
       c.set(Calendar.SECOND, 59);
       c.set(Calendar.MILLISECOND, 999);
       return c.getTime();
   }
   /** 
    * Returns the maximum of two dates. A null date is treated as being less
    * than any non-null date. 
    */
   public static Date max(Date d1, Date d2) {
       if (d1 == null && d2 == null) return null;
       if (d1 == null) return d2;
       if (d2 == null) return d1;
       return (d1.after(d2)) ? d1 : d2;
   }
   
   /** 
    * Returns the minimum of two dates. A null date is treated as being greater
    * than any non-null date. 
    */
   public static Date min(Date d1, Date d2) {
       if (d1 == null && d2 == null) return null;
       if (d1 == null) return d2;
       if (d2 == null) return d1;
       return (d1.before(d2)) ? d1 : d2;
   }
   /** The maximum date possible. */
   public static Date MAX_DATE = new Date(Long.MAX_VALUE);
   

}


 </source>
   
  
 
  



Checks if a calendar date is today

   <source lang="java">
  

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

   /**
*

Checks if two dates are on the same day ignoring time.

    * @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
    */
   public static boolean isSameDay(Date date1, Date date2) {
       if (date1 == null || date2 == null) {
           throw new IllegalArgumentException("The dates 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 calendars represent the same day ignoring time.

    * @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
    */
   public static boolean isSameDay(Calendar cal1, Calendar cal2) {
       if (cal1 == null || cal2 == null) {
           throw new IllegalArgumentException("The dates 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));
   }
   
   /**
*

Checks if a date is today.

    * @param date the date, not altered, not null.
    * @return true if the date is today.
    * @throws IllegalArgumentException if the date is null
    */
   public static boolean isToday(Date date) {
       return isSameDay(date, Calendar.getInstance().getTime());
   }
   
   /**
*

Checks if a calendar date is today.

    * @param cal  the calendar, not altered, not null
    * @return true if cal date is today
    * @throws IllegalArgumentException if the calendar is null
    */
   public static boolean isToday(Calendar cal) {
       return isSameDay(cal, Calendar.getInstance());
   }
   
   /**
*

Checks if the first date is before the second date ignoring time.

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

Checks if the first calendar date is before the second calendar date ignoring time.

    * @param cal1 the first calendar, not altered, not null.
    * @param cal2 the second calendar, not altered, not null.
    * @return true if cal1 date is before cal2 date ignoring time.
    * @throws IllegalArgumentException if either of the calendars are null
    */
   public static boolean isBeforeDay(Calendar cal1, Calendar cal2) {
       if (cal1 == null || cal2 == null) {
           throw new IllegalArgumentException("The dates must not be null");
       }
       if (cal1.get(Calendar.ERA) < cal2.get(Calendar.ERA)) return true;
       if (cal1.get(Calendar.ERA) > cal2.get(Calendar.ERA)) return false;
       if (cal1.get(Calendar.YEAR) < cal2.get(Calendar.YEAR)) return true;
       if (cal1.get(Calendar.YEAR) > cal2.get(Calendar.YEAR)) return false;
       return cal1.get(Calendar.DAY_OF_YEAR) < cal2.get(Calendar.DAY_OF_YEAR);
   }
   
   /**
*

Checks if the first date is after the second date ignoring time.

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

Checks if the first calendar date is after the second calendar date ignoring time.

    * @param cal1 the first calendar, not altered, not null.
    * @param cal2 the second calendar, not altered, not null.
    * @return true if cal1 date is after cal2 date ignoring time.
    * @throws IllegalArgumentException if either of the calendars are null
    */
   public static boolean isAfterDay(Calendar cal1, Calendar cal2) {
       if (cal1 == null || cal2 == null) {
           throw new IllegalArgumentException("The dates must not be null");
       }
       if (cal1.get(Calendar.ERA) < cal2.get(Calendar.ERA)) return false;
       if (cal1.get(Calendar.ERA) > cal2.get(Calendar.ERA)) return true;
       if (cal1.get(Calendar.YEAR) < cal2.get(Calendar.YEAR)) return false;
       if (cal1.get(Calendar.YEAR) > cal2.get(Calendar.YEAR)) return true;
       return cal1.get(Calendar.DAY_OF_YEAR) > cal2.get(Calendar.DAY_OF_YEAR);
   }
   
   /**
*

Checks if a date is after today and within a number of days in the future.

    * @param date the date to check, not altered, not null.
    * @param days the number of days.
    * @return true if the date day is after today and within days in the future .
    * @throws IllegalArgumentException if the date is null
    */
   public static boolean isWithinDaysFuture(Date date, int days) {
       if (date == null) {
           throw new IllegalArgumentException("The date must not be null");
       }
       Calendar cal = Calendar.getInstance();
       cal.setTime(date);
       return isWithinDaysFuture(cal, days);
   }
   
   /**
*

Checks if a calendar date is after today and within a number of days in the future.

    * @param cal the calendar, not altered, not null
    * @param days the number of days.
    * @return true if the calendar date day is after today and within days in the future .
    * @throws IllegalArgumentException if the calendar is null
    */
   public static boolean isWithinDaysFuture(Calendar cal, int days) {
       if (cal == null) {
           throw new IllegalArgumentException("The date must not be null");
       }
       Calendar today = Calendar.getInstance();
       Calendar future = Calendar.getInstance();
       future.add(Calendar.DAY_OF_YEAR, days);
       return (isAfterDay(cal, today) && ! isAfterDay(cal, future));
   }
   
   /** Returns the given date with the time set to the start of the day. */
   public static Date getStart(Date date) {
       return clearTime(date);
   }
   
   /** Returns the given date with the time values cleared. */
   public static Date clearTime(Date date) {
       if (date == null) {
           return null;
       }
       Calendar c = Calendar.getInstance();
       c.setTime(date);
       c.set(Calendar.HOUR_OF_DAY, 0);
       c.set(Calendar.MINUTE, 0);
       c.set(Calendar.SECOND, 0);
       c.set(Calendar.MILLISECOND, 0);
       return c.getTime();
   }    
   /** Determines whether or not a date has any time values (hour, minute, 
    * seconds or millisecondsReturns the given date with the time values cleared. */
   /**
    * Determines whether or not a date has any time values.
    * @param date The date.
    * @return true iff the date is not null and any of the date"s hour, minute,
    * seconds or millisecond values are greater than zero.
    */
   public static boolean hasTime(Date date) {
       if (date == null) {
           return false;
       }
       Calendar c = Calendar.getInstance();
       c.setTime(date);
       if (c.get(Calendar.HOUR_OF_DAY) > 0) {
           return true;
       }
       if (c.get(Calendar.MINUTE) > 0) {
           return true;
       }
       if (c.get(Calendar.SECOND) > 0) {
           return true;
       }
       if (c.get(Calendar.MILLISECOND) > 0) {
           return true;
       }
       return false;
   }
   /** Returns the given date with time set to the end of the day */
   public static Date getEnd(Date date) {
       if (date == null) {
           return null;
       }
       Calendar c = Calendar.getInstance();
       c.setTime(date);
       c.set(Calendar.HOUR_OF_DAY, 23);
       c.set(Calendar.MINUTE, 59);
       c.set(Calendar.SECOND, 59);
       c.set(Calendar.MILLISECOND, 999);
       return c.getTime();
   }
   /** 
    * Returns the maximum of two dates. A null date is treated as being less
    * than any non-null date. 
    */
   public static Date max(Date d1, Date d2) {
       if (d1 == null && d2 == null) return null;
       if (d1 == null) return d2;
       if (d2 == null) return d1;
       return (d1.after(d2)) ? d1 : d2;
   }
   
   /** 
    * Returns the minimum of two dates. A null date is treated as being greater
    * than any non-null date. 
    */
   public static Date min(Date d1, Date d2) {
       if (d1 == null && d2 == null) return null;
       if (d1 == null) return d2;
       if (d2 == null) return d1;
       return (d1.before(d2)) ? d1 : d2;
   }
   /** The maximum date possible. */
   public static Date MAX_DATE = new Date(Long.MAX_VALUE);
   

}


 </source>
   
  
 
  



Checks if a date is after today and within a number of days in the future

   <source lang="java">
  

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

   /**
*

Checks if two dates are on the same day ignoring time.

    * @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
    */
   public static boolean isSameDay(Date date1, Date date2) {
       if (date1 == null || date2 == null) {
           throw new IllegalArgumentException("The dates 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 calendars represent the same day ignoring time.

    * @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
    */
   public static boolean isSameDay(Calendar cal1, Calendar cal2) {
       if (cal1 == null || cal2 == null) {
           throw new IllegalArgumentException("The dates 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));
   }
   
   /**
*

Checks if a date is today.

    * @param date the date, not altered, not null.
    * @return true if the date is today.
    * @throws IllegalArgumentException if the date is null
    */
   public static boolean isToday(Date date) {
       return isSameDay(date, Calendar.getInstance().getTime());
   }
   
   /**
*

Checks if a calendar date is today.

    * @param cal  the calendar, not altered, not null
    * @return true if cal date is today
    * @throws IllegalArgumentException if the calendar is null
    */
   public static boolean isToday(Calendar cal) {
       return isSameDay(cal, Calendar.getInstance());
   }
   
   /**
*

Checks if the first date is before the second date ignoring time.

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

Checks if the first calendar date is before the second calendar date ignoring time.

    * @param cal1 the first calendar, not altered, not null.
    * @param cal2 the second calendar, not altered, not null.
    * @return true if cal1 date is before cal2 date ignoring time.
    * @throws IllegalArgumentException if either of the calendars are null
    */
   public static boolean isBeforeDay(Calendar cal1, Calendar cal2) {
       if (cal1 == null || cal2 == null) {
           throw new IllegalArgumentException("The dates must not be null");
       }
       if (cal1.get(Calendar.ERA) < cal2.get(Calendar.ERA)) return true;
       if (cal1.get(Calendar.ERA) > cal2.get(Calendar.ERA)) return false;
       if (cal1.get(Calendar.YEAR) < cal2.get(Calendar.YEAR)) return true;
       if (cal1.get(Calendar.YEAR) > cal2.get(Calendar.YEAR)) return false;
       return cal1.get(Calendar.DAY_OF_YEAR) < cal2.get(Calendar.DAY_OF_YEAR);
   }
   
   /**
*

Checks if the first date is after the second date ignoring time.

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

Checks if the first calendar date is after the second calendar date ignoring time.

    * @param cal1 the first calendar, not altered, not null.
    * @param cal2 the second calendar, not altered, not null.
    * @return true if cal1 date is after cal2 date ignoring time.
    * @throws IllegalArgumentException if either of the calendars are null
    */
   public static boolean isAfterDay(Calendar cal1, Calendar cal2) {
       if (cal1 == null || cal2 == null) {
           throw new IllegalArgumentException("The dates must not be null");
       }
       if (cal1.get(Calendar.ERA) < cal2.get(Calendar.ERA)) return false;
       if (cal1.get(Calendar.ERA) > cal2.get(Calendar.ERA)) return true;
       if (cal1.get(Calendar.YEAR) < cal2.get(Calendar.YEAR)) return false;
       if (cal1.get(Calendar.YEAR) > cal2.get(Calendar.YEAR)) return true;
       return cal1.get(Calendar.DAY_OF_YEAR) > cal2.get(Calendar.DAY_OF_YEAR);
   }
   
   /**
*

Checks if a date is after today and within a number of days in the future.

    * @param date the date to check, not altered, not null.
    * @param days the number of days.
    * @return true if the date day is after today and within days in the future .
    * @throws IllegalArgumentException if the date is null
    */
   public static boolean isWithinDaysFuture(Date date, int days) {
       if (date == null) {
           throw new IllegalArgumentException("The date must not be null");
       }
       Calendar cal = Calendar.getInstance();
       cal.setTime(date);
       return isWithinDaysFuture(cal, days);
   }
   
   /**
*

Checks if a calendar date is after today and within a number of days in the future.

    * @param cal the calendar, not altered, not null
    * @param days the number of days.
    * @return true if the calendar date day is after today and within days in the future .
    * @throws IllegalArgumentException if the calendar is null
    */
   public static boolean isWithinDaysFuture(Calendar cal, int days) {
       if (cal == null) {
           throw new IllegalArgumentException("The date must not be null");
       }
       Calendar today = Calendar.getInstance();
       Calendar future = Calendar.getInstance();
       future.add(Calendar.DAY_OF_YEAR, days);
       return (isAfterDay(cal, today) && ! isAfterDay(cal, future));
   }
   
   /** Returns the given date with the time set to the start of the day. */
   public static Date getStart(Date date) {
       return clearTime(date);
   }
   
   /** Returns the given date with the time values cleared. */
   public static Date clearTime(Date date) {
       if (date == null) {
           return null;
       }
       Calendar c = Calendar.getInstance();
       c.setTime(date);
       c.set(Calendar.HOUR_OF_DAY, 0);
       c.set(Calendar.MINUTE, 0);
       c.set(Calendar.SECOND, 0);
       c.set(Calendar.MILLISECOND, 0);
       return c.getTime();
   }    
   /** Determines whether or not a date has any time values (hour, minute, 
    * seconds or millisecondsReturns the given date with the time values cleared. */
   /**
    * Determines whether or not a date has any time values.
    * @param date The date.
    * @return true iff the date is not null and any of the date"s hour, minute,
    * seconds or millisecond values are greater than zero.
    */
   public static boolean hasTime(Date date) {
       if (date == null) {
           return false;
       }
       Calendar c = Calendar.getInstance();
       c.setTime(date);
       if (c.get(Calendar.HOUR_OF_DAY) > 0) {
           return true;
       }
       if (c.get(Calendar.MINUTE) > 0) {
           return true;
       }
       if (c.get(Calendar.SECOND) > 0) {
           return true;
       }
       if (c.get(Calendar.MILLISECOND) > 0) {
           return true;
       }
       return false;
   }
   /** Returns the given date with time set to the end of the day */
   public static Date getEnd(Date date) {
       if (date == null) {
           return null;
       }
       Calendar c = Calendar.getInstance();
       c.setTime(date);
       c.set(Calendar.HOUR_OF_DAY, 23);
       c.set(Calendar.MINUTE, 59);
       c.set(Calendar.SECOND, 59);
       c.set(Calendar.MILLISECOND, 999);
       return c.getTime();
   }
   /** 
    * Returns the maximum of two dates. A null date is treated as being less
    * than any non-null date. 
    */
   public static Date max(Date d1, Date d2) {
       if (d1 == null && d2 == null) return null;
       if (d1 == null) return d2;
       if (d2 == null) return d1;
       return (d1.after(d2)) ? d1 : d2;
   }
   
   /** 
    * Returns the minimum of two dates. A null date is treated as being greater
    * than any non-null date. 
    */
   public static Date min(Date d1, Date d2) {
       if (d1 == null && d2 == null) return null;
       if (d1 == null) return d2;
       if (d2 == null) return d1;
       return (d1.before(d2)) ? d1 : d2;
   }
   /** The maximum date possible. */
   public static Date MAX_DATE = new Date(Long.MAX_VALUE);
   

}


 </source>
   
  
 
  



Checks if the first calendar date is after the second calendar date ignoring time

   <source lang="java">
  

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

   /**
*

Checks if two dates are on the same day ignoring time.

    * @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
    */
   public static boolean isSameDay(Date date1, Date date2) {
       if (date1 == null || date2 == null) {
           throw new IllegalArgumentException("The dates 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 calendars represent the same day ignoring time.

    * @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
    */
   public static boolean isSameDay(Calendar cal1, Calendar cal2) {
       if (cal1 == null || cal2 == null) {
           throw new IllegalArgumentException("The dates 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));
   }
   
   /**
*

Checks if a date is today.

    * @param date the date, not altered, not null.
    * @return true if the date is today.
    * @throws IllegalArgumentException if the date is null
    */
   public static boolean isToday(Date date) {
       return isSameDay(date, Calendar.getInstance().getTime());
   }
   
   /**
*

Checks if a calendar date is today.

    * @param cal  the calendar, not altered, not null
    * @return true if cal date is today
    * @throws IllegalArgumentException if the calendar is null
    */
   public static boolean isToday(Calendar cal) {
       return isSameDay(cal, Calendar.getInstance());
   }
   
   /**
*

Checks if the first date is before the second date ignoring time.

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

Checks if the first calendar date is before the second calendar date ignoring time.

    * @param cal1 the first calendar, not altered, not null.
    * @param cal2 the second calendar, not altered, not null.
    * @return true if cal1 date is before cal2 date ignoring time.
    * @throws IllegalArgumentException if either of the calendars are null
    */
   public static boolean isBeforeDay(Calendar cal1, Calendar cal2) {
       if (cal1 == null || cal2 == null) {
           throw new IllegalArgumentException("The dates must not be null");
       }
       if (cal1.get(Calendar.ERA) < cal2.get(Calendar.ERA)) return true;
       if (cal1.get(Calendar.ERA) > cal2.get(Calendar.ERA)) return false;
       if (cal1.get(Calendar.YEAR) < cal2.get(Calendar.YEAR)) return true;
       if (cal1.get(Calendar.YEAR) > cal2.get(Calendar.YEAR)) return false;
       return cal1.get(Calendar.DAY_OF_YEAR) < cal2.get(Calendar.DAY_OF_YEAR);
   }
   
   /**
*

Checks if the first date is after the second date ignoring time.

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

Checks if the first calendar date is after the second calendar date ignoring time.

    * @param cal1 the first calendar, not altered, not null.
    * @param cal2 the second calendar, not altered, not null.
    * @return true if cal1 date is after cal2 date ignoring time.
    * @throws IllegalArgumentException if either of the calendars are null
    */
   public static boolean isAfterDay(Calendar cal1, Calendar cal2) {
       if (cal1 == null || cal2 == null) {
           throw new IllegalArgumentException("The dates must not be null");
       }
       if (cal1.get(Calendar.ERA) < cal2.get(Calendar.ERA)) return false;
       if (cal1.get(Calendar.ERA) > cal2.get(Calendar.ERA)) return true;
       if (cal1.get(Calendar.YEAR) < cal2.get(Calendar.YEAR)) return false;
       if (cal1.get(Calendar.YEAR) > cal2.get(Calendar.YEAR)) return true;
       return cal1.get(Calendar.DAY_OF_YEAR) > cal2.get(Calendar.DAY_OF_YEAR);
   }
   
   /**
*

Checks if a date is after today and within a number of days in the future.

    * @param date the date to check, not altered, not null.
    * @param days the number of days.
    * @return true if the date day is after today and within days in the future .
    * @throws IllegalArgumentException if the date is null
    */
   public static boolean isWithinDaysFuture(Date date, int days) {
       if (date == null) {
           throw new IllegalArgumentException("The date must not be null");
       }
       Calendar cal = Calendar.getInstance();
       cal.setTime(date);
       return isWithinDaysFuture(cal, days);
   }
   
   /**
*

Checks if a calendar date is after today and within a number of days in the future.

    * @param cal the calendar, not altered, not null
    * @param days the number of days.
    * @return true if the calendar date day is after today and within days in the future .
    * @throws IllegalArgumentException if the calendar is null
    */
   public static boolean isWithinDaysFuture(Calendar cal, int days) {
       if (cal == null) {
           throw new IllegalArgumentException("The date must not be null");
       }
       Calendar today = Calendar.getInstance();
       Calendar future = Calendar.getInstance();
       future.add(Calendar.DAY_OF_YEAR, days);
       return (isAfterDay(cal, today) && ! isAfterDay(cal, future));
   }
   
   /** Returns the given date with the time set to the start of the day. */
   public static Date getStart(Date date) {
       return clearTime(date);
   }
   
   /** Returns the given date with the time values cleared. */
   public static Date clearTime(Date date) {
       if (date == null) {
           return null;
       }
       Calendar c = Calendar.getInstance();
       c.setTime(date);
       c.set(Calendar.HOUR_OF_DAY, 0);
       c.set(Calendar.MINUTE, 0);
       c.set(Calendar.SECOND, 0);
       c.set(Calendar.MILLISECOND, 0);
       return c.getTime();
   }    
   /** Determines whether or not a date has any time values (hour, minute, 
    * seconds or millisecondsReturns the given date with the time values cleared. */
   /**
    * Determines whether or not a date has any time values.
    * @param date The date.
    * @return true iff the date is not null and any of the date"s hour, minute,
    * seconds or millisecond values are greater than zero.
    */
   public static boolean hasTime(Date date) {
       if (date == null) {
           return false;
       }
       Calendar c = Calendar.getInstance();
       c.setTime(date);
       if (c.get(Calendar.HOUR_OF_DAY) > 0) {
           return true;
       }
       if (c.get(Calendar.MINUTE) > 0) {
           return true;
       }
       if (c.get(Calendar.SECOND) > 0) {
           return true;
       }
       if (c.get(Calendar.MILLISECOND) > 0) {
           return true;
       }
       return false;
   }
   /** Returns the given date with time set to the end of the day */
   public static Date getEnd(Date date) {
       if (date == null) {
           return null;
       }
       Calendar c = Calendar.getInstance();
       c.setTime(date);
       c.set(Calendar.HOUR_OF_DAY, 23);
       c.set(Calendar.MINUTE, 59);
       c.set(Calendar.SECOND, 59);
       c.set(Calendar.MILLISECOND, 999);
       return c.getTime();
   }
   /** 
    * Returns the maximum of two dates. A null date is treated as being less
    * than any non-null date. 
    */
   public static Date max(Date d1, Date d2) {
       if (d1 == null && d2 == null) return null;
       if (d1 == null) return d2;
       if (d2 == null) return d1;
       return (d1.after(d2)) ? d1 : d2;
   }
   
   /** 
    * Returns the minimum of two dates. A null date is treated as being greater
    * than any non-null date. 
    */
   public static Date min(Date d1, Date d2) {
       if (d1 == null && d2 == null) return null;
       if (d1 == null) return d2;
       if (d2 == null) return d1;
       return (d1.before(d2)) ? d1 : d2;
   }
   /** The maximum date possible. */
   public static Date MAX_DATE = new Date(Long.MAX_VALUE);
   

}


 </source>
   
  
 
  



Checks if the first calendar date is before the second calendar date ignoring time

   <source lang="java">
  

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

   /**
*

Checks if two dates are on the same day ignoring time.

    * @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
    */
   public static boolean isSameDay(Date date1, Date date2) {
       if (date1 == null || date2 == null) {
           throw new IllegalArgumentException("The dates 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 calendars represent the same day ignoring time.

    * @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
    */
   public static boolean isSameDay(Calendar cal1, Calendar cal2) {
       if (cal1 == null || cal2 == null) {
           throw new IllegalArgumentException("The dates 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));
   }
   
   /**
*

Checks if a date is today.

    * @param date the date, not altered, not null.
    * @return true if the date is today.
    * @throws IllegalArgumentException if the date is null
    */
   public static boolean isToday(Date date) {
       return isSameDay(date, Calendar.getInstance().getTime());
   }
   
   /**
*

Checks if a calendar date is today.

    * @param cal  the calendar, not altered, not null
    * @return true if cal date is today
    * @throws IllegalArgumentException if the calendar is null
    */
   public static boolean isToday(Calendar cal) {
       return isSameDay(cal, Calendar.getInstance());
   }
   
   /**
*

Checks if the first date is before the second date ignoring time.

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

Checks if the first calendar date is before the second calendar date ignoring time.

    * @param cal1 the first calendar, not altered, not null.
    * @param cal2 the second calendar, not altered, not null.
    * @return true if cal1 date is before cal2 date ignoring time.
    * @throws IllegalArgumentException if either of the calendars are null
    */
   public static boolean isBeforeDay(Calendar cal1, Calendar cal2) {
       if (cal1 == null || cal2 == null) {
           throw new IllegalArgumentException("The dates must not be null");
       }
       if (cal1.get(Calendar.ERA) < cal2.get(Calendar.ERA)) return true;
       if (cal1.get(Calendar.ERA) > cal2.get(Calendar.ERA)) return false;
       if (cal1.get(Calendar.YEAR) < cal2.get(Calendar.YEAR)) return true;
       if (cal1.get(Calendar.YEAR) > cal2.get(Calendar.YEAR)) return false;
       return cal1.get(Calendar.DAY_OF_YEAR) < cal2.get(Calendar.DAY_OF_YEAR);
   }
   
   /**
*

Checks if the first date is after the second date ignoring time.

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

Checks if the first calendar date is after the second calendar date ignoring time.

    * @param cal1 the first calendar, not altered, not null.
    * @param cal2 the second calendar, not altered, not null.
    * @return true if cal1 date is after cal2 date ignoring time.
    * @throws IllegalArgumentException if either of the calendars are null
    */
   public static boolean isAfterDay(Calendar cal1, Calendar cal2) {
       if (cal1 == null || cal2 == null) {
           throw new IllegalArgumentException("The dates must not be null");
       }
       if (cal1.get(Calendar.ERA) < cal2.get(Calendar.ERA)) return false;
       if (cal1.get(Calendar.ERA) > cal2.get(Calendar.ERA)) return true;
       if (cal1.get(Calendar.YEAR) < cal2.get(Calendar.YEAR)) return false;
       if (cal1.get(Calendar.YEAR) > cal2.get(Calendar.YEAR)) return true;
       return cal1.get(Calendar.DAY_OF_YEAR) > cal2.get(Calendar.DAY_OF_YEAR);
   }
   
   /**
*

Checks if a date is after today and within a number of days in the future.

    * @param date the date to check, not altered, not null.
    * @param days the number of days.
    * @return true if the date day is after today and within days in the future .
    * @throws IllegalArgumentException if the date is null
    */
   public static boolean isWithinDaysFuture(Date date, int days) {
       if (date == null) {
           throw new IllegalArgumentException("The date must not be null");
       }
       Calendar cal = Calendar.getInstance();
       cal.setTime(date);
       return isWithinDaysFuture(cal, days);
   }
   
   /**
*

Checks if a calendar date is after today and within a number of days in the future.

    * @param cal the calendar, not altered, not null
    * @param days the number of days.
    * @return true if the calendar date day is after today and within days in the future .
    * @throws IllegalArgumentException if the calendar is null
    */
   public static boolean isWithinDaysFuture(Calendar cal, int days) {
       if (cal == null) {
           throw new IllegalArgumentException("The date must not be null");
       }
       Calendar today = Calendar.getInstance();
       Calendar future = Calendar.getInstance();
       future.add(Calendar.DAY_OF_YEAR, days);
       return (isAfterDay(cal, today) && ! isAfterDay(cal, future));
   }
   
   /** Returns the given date with the time set to the start of the day. */
   public static Date getStart(Date date) {
       return clearTime(date);
   }
   
   /** Returns the given date with the time values cleared. */
   public static Date clearTime(Date date) {
       if (date == null) {
           return null;
       }
       Calendar c = Calendar.getInstance();
       c.setTime(date);
       c.set(Calendar.HOUR_OF_DAY, 0);
       c.set(Calendar.MINUTE, 0);
       c.set(Calendar.SECOND, 0);
       c.set(Calendar.MILLISECOND, 0);
       return c.getTime();
   }    
   /** Determines whether or not a date has any time values (hour, minute, 
    * seconds or millisecondsReturns the given date with the time values cleared. */
   /**
    * Determines whether or not a date has any time values.
    * @param date The date.
    * @return true iff the date is not null and any of the date"s hour, minute,
    * seconds or millisecond values are greater than zero.
    */
   public static boolean hasTime(Date date) {
       if (date == null) {
           return false;
       }
       Calendar c = Calendar.getInstance();
       c.setTime(date);
       if (c.get(Calendar.HOUR_OF_DAY) > 0) {
           return true;
       }
       if (c.get(Calendar.MINUTE) > 0) {
           return true;
       }
       if (c.get(Calendar.SECOND) > 0) {
           return true;
       }
       if (c.get(Calendar.MILLISECOND) > 0) {
           return true;
       }
       return false;
   }
   /** Returns the given date with time set to the end of the day */
   public static Date getEnd(Date date) {
       if (date == null) {
           return null;
       }
       Calendar c = Calendar.getInstance();
       c.setTime(date);
       c.set(Calendar.HOUR_OF_DAY, 23);
       c.set(Calendar.MINUTE, 59);
       c.set(Calendar.SECOND, 59);
       c.set(Calendar.MILLISECOND, 999);
       return c.getTime();
   }
   /** 
    * Returns the maximum of two dates. A null date is treated as being less
    * than any non-null date. 
    */
   public static Date max(Date d1, Date d2) {
       if (d1 == null && d2 == null) return null;
       if (d1 == null) return d2;
       if (d2 == null) return d1;
       return (d1.after(d2)) ? d1 : d2;
   }
   
   /** 
    * Returns the minimum of two dates. A null date is treated as being greater
    * than any non-null date. 
    */
   public static Date min(Date d1, Date d2) {
       if (d1 == null && d2 == null) return null;
       if (d1 == null) return d2;
       if (d2 == null) return d1;
       return (d1.before(d2)) ? d1 : d2;
   }
   /** The maximum date possible. */
   public static Date MAX_DATE = new Date(Long.MAX_VALUE);
   

}


 </source>
   
  
 
  



Checks if the first date is after the second date ignoring time

   <source lang="java">
  

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

   /**
*

Checks if two dates are on the same day ignoring time.

    * @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
    */
   public static boolean isSameDay(Date date1, Date date2) {
       if (date1 == null || date2 == null) {
           throw new IllegalArgumentException("The dates 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 calendars represent the same day ignoring time.

    * @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
    */
   public static boolean isSameDay(Calendar cal1, Calendar cal2) {
       if (cal1 == null || cal2 == null) {
           throw new IllegalArgumentException("The dates 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));
   }
   
   /**
*

Checks if a date is today.

    * @param date the date, not altered, not null.
    * @return true if the date is today.
    * @throws IllegalArgumentException if the date is null
    */
   public static boolean isToday(Date date) {
       return isSameDay(date, Calendar.getInstance().getTime());
   }
   
   /**
*

Checks if a calendar date is today.

    * @param cal  the calendar, not altered, not null
    * @return true if cal date is today
    * @throws IllegalArgumentException if the calendar is null
    */
   public static boolean isToday(Calendar cal) {
       return isSameDay(cal, Calendar.getInstance());
   }
   
   /**
*

Checks if the first date is before the second date ignoring time.

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

Checks if the first calendar date is before the second calendar date ignoring time.

    * @param cal1 the first calendar, not altered, not null.
    * @param cal2 the second calendar, not altered, not null.
    * @return true if cal1 date is before cal2 date ignoring time.
    * @throws IllegalArgumentException if either of the calendars are null
    */
   public static boolean isBeforeDay(Calendar cal1, Calendar cal2) {
       if (cal1 == null || cal2 == null) {
           throw new IllegalArgumentException("The dates must not be null");
       }
       if (cal1.get(Calendar.ERA) < cal2.get(Calendar.ERA)) return true;
       if (cal1.get(Calendar.ERA) > cal2.get(Calendar.ERA)) return false;
       if (cal1.get(Calendar.YEAR) < cal2.get(Calendar.YEAR)) return true;
       if (cal1.get(Calendar.YEAR) > cal2.get(Calendar.YEAR)) return false;
       return cal1.get(Calendar.DAY_OF_YEAR) < cal2.get(Calendar.DAY_OF_YEAR);
   }
   
   /**
*

Checks if the first date is after the second date ignoring time.

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

Checks if the first calendar date is after the second calendar date ignoring time.

    * @param cal1 the first calendar, not altered, not null.
    * @param cal2 the second calendar, not altered, not null.
    * @return true if cal1 date is after cal2 date ignoring time.
    * @throws IllegalArgumentException if either of the calendars are null
    */
   public static boolean isAfterDay(Calendar cal1, Calendar cal2) {
       if (cal1 == null || cal2 == null) {
           throw new IllegalArgumentException("The dates must not be null");
       }
       if (cal1.get(Calendar.ERA) < cal2.get(Calendar.ERA)) return false;
       if (cal1.get(Calendar.ERA) > cal2.get(Calendar.ERA)) return true;
       if (cal1.get(Calendar.YEAR) < cal2.get(Calendar.YEAR)) return false;
       if (cal1.get(Calendar.YEAR) > cal2.get(Calendar.YEAR)) return true;
       return cal1.get(Calendar.DAY_OF_YEAR) > cal2.get(Calendar.DAY_OF_YEAR);
   }
   
   /**
*

Checks if a date is after today and within a number of days in the future.

    * @param date the date to check, not altered, not null.
    * @param days the number of days.
    * @return true if the date day is after today and within days in the future .
    * @throws IllegalArgumentException if the date is null
    */
   public static boolean isWithinDaysFuture(Date date, int days) {
       if (date == null) {
           throw new IllegalArgumentException("The date must not be null");
       }
       Calendar cal = Calendar.getInstance();
       cal.setTime(date);
       return isWithinDaysFuture(cal, days);
   }
   
   /**
*

Checks if a calendar date is after today and within a number of days in the future.

    * @param cal the calendar, not altered, not null
    * @param days the number of days.
    * @return true if the calendar date day is after today and within days in the future .
    * @throws IllegalArgumentException if the calendar is null
    */
   public static boolean isWithinDaysFuture(Calendar cal, int days) {
       if (cal == null) {
           throw new IllegalArgumentException("The date must not be null");
       }
       Calendar today = Calendar.getInstance();
       Calendar future = Calendar.getInstance();
       future.add(Calendar.DAY_OF_YEAR, days);
       return (isAfterDay(cal, today) && ! isAfterDay(cal, future));
   }
   
   /** Returns the given date with the time set to the start of the day. */
   public static Date getStart(Date date) {
       return clearTime(date);
   }
   
   /** Returns the given date with the time values cleared. */
   public static Date clearTime(Date date) {
       if (date == null) {
           return null;
       }
       Calendar c = Calendar.getInstance();
       c.setTime(date);
       c.set(Calendar.HOUR_OF_DAY, 0);
       c.set(Calendar.MINUTE, 0);
       c.set(Calendar.SECOND, 0);
       c.set(Calendar.MILLISECOND, 0);
       return c.getTime();
   }    
   /** Determines whether or not a date has any time values (hour, minute, 
    * seconds or millisecondsReturns the given date with the time values cleared. */
   /**
    * Determines whether or not a date has any time values.
    * @param date The date.
    * @return true iff the date is not null and any of the date"s hour, minute,
    * seconds or millisecond values are greater than zero.
    */
   public static boolean hasTime(Date date) {
       if (date == null) {
           return false;
       }
       Calendar c = Calendar.getInstance();
       c.setTime(date);
       if (c.get(Calendar.HOUR_OF_DAY) > 0) {
           return true;
       }
       if (c.get(Calendar.MINUTE) > 0) {
           return true;
       }
       if (c.get(Calendar.SECOND) > 0) {
           return true;
       }
       if (c.get(Calendar.MILLISECOND) > 0) {
           return true;
       }
       return false;
   }
   /** Returns the given date with time set to the end of the day */
   public static Date getEnd(Date date) {
       if (date == null) {
           return null;
       }
       Calendar c = Calendar.getInstance();
       c.setTime(date);
       c.set(Calendar.HOUR_OF_DAY, 23);
       c.set(Calendar.MINUTE, 59);
       c.set(Calendar.SECOND, 59);
       c.set(Calendar.MILLISECOND, 999);
       return c.getTime();
   }
   /** 
    * Returns the maximum of two dates. A null date is treated as being less
    * than any non-null date. 
    */
   public static Date max(Date d1, Date d2) {
       if (d1 == null && d2 == null) return null;
       if (d1 == null) return d2;
       if (d2 == null) return d1;
       return (d1.after(d2)) ? d1 : d2;
   }
   
   /** 
    * Returns the minimum of two dates. A null date is treated as being greater
    * than any non-null date. 
    */
   public static Date min(Date d1, Date d2) {
       if (d1 == null && d2 == null) return null;
       if (d1 == null) return d2;
       if (d2 == null) return d1;
       return (d1.before(d2)) ? d1 : d2;
   }
   /** The maximum date possible. */
   public static Date MAX_DATE = new Date(Long.MAX_VALUE);
   

}


 </source>
   
  
 
  



Checks if the first date is before the second date ignoring time

   <source lang="java">
  

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

   /**
*

Checks if two dates are on the same day ignoring time.

    * @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
    */
   public static boolean isSameDay(Date date1, Date date2) {
       if (date1 == null || date2 == null) {
           throw new IllegalArgumentException("The dates 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 calendars represent the same day ignoring time.

    * @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
    */
   public static boolean isSameDay(Calendar cal1, Calendar cal2) {
       if (cal1 == null || cal2 == null) {
           throw new IllegalArgumentException("The dates 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));
   }
   
   /**
*

Checks if a date is today.

    * @param date the date, not altered, not null.
    * @return true if the date is today.
    * @throws IllegalArgumentException if the date is null
    */
   public static boolean isToday(Date date) {
       return isSameDay(date, Calendar.getInstance().getTime());
   }
   
   /**
*

Checks if a calendar date is today.

    * @param cal  the calendar, not altered, not null
    * @return true if cal date is today
    * @throws IllegalArgumentException if the calendar is null
    */
   public static boolean isToday(Calendar cal) {
       return isSameDay(cal, Calendar.getInstance());
   }
   
   /**
*

Checks if the first date is before the second date ignoring time.

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

Checks if the first calendar date is before the second calendar date ignoring time.

    * @param cal1 the first calendar, not altered, not null.
    * @param cal2 the second calendar, not altered, not null.
    * @return true if cal1 date is before cal2 date ignoring time.
    * @throws IllegalArgumentException if either of the calendars are null
    */
   public static boolean isBeforeDay(Calendar cal1, Calendar cal2) {
       if (cal1 == null || cal2 == null) {
           throw new IllegalArgumentException("The dates must not be null");
       }
       if (cal1.get(Calendar.ERA) < cal2.get(Calendar.ERA)) return true;
       if (cal1.get(Calendar.ERA) > cal2.get(Calendar.ERA)) return false;
       if (cal1.get(Calendar.YEAR) < cal2.get(Calendar.YEAR)) return true;
       if (cal1.get(Calendar.YEAR) > cal2.get(Calendar.YEAR)) return false;
       return cal1.get(Calendar.DAY_OF_YEAR) < cal2.get(Calendar.DAY_OF_YEAR);
   }
   
   /**
*

Checks if the first date is after the second date ignoring time.

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

Checks if the first calendar date is after the second calendar date ignoring time.

    * @param cal1 the first calendar, not altered, not null.
    * @param cal2 the second calendar, not altered, not null.
    * @return true if cal1 date is after cal2 date ignoring time.
    * @throws IllegalArgumentException if either of the calendars are null
    */
   public static boolean isAfterDay(Calendar cal1, Calendar cal2) {
       if (cal1 == null || cal2 == null) {
           throw new IllegalArgumentException("The dates must not be null");
       }
       if (cal1.get(Calendar.ERA) < cal2.get(Calendar.ERA)) return false;
       if (cal1.get(Calendar.ERA) > cal2.get(Calendar.ERA)) return true;
       if (cal1.get(Calendar.YEAR) < cal2.get(Calendar.YEAR)) return false;
       if (cal1.get(Calendar.YEAR) > cal2.get(Calendar.YEAR)) return true;
       return cal1.get(Calendar.DAY_OF_YEAR) > cal2.get(Calendar.DAY_OF_YEAR);
   }
   
   /**
*

Checks if a date is after today and within a number of days in the future.

    * @param date the date to check, not altered, not null.
    * @param days the number of days.
    * @return true if the date day is after today and within days in the future .
    * @throws IllegalArgumentException if the date is null
    */
   public static boolean isWithinDaysFuture(Date date, int days) {
       if (date == null) {
           throw new IllegalArgumentException("The date must not be null");
       }
       Calendar cal = Calendar.getInstance();
       cal.setTime(date);
       return isWithinDaysFuture(cal, days);
   }
   
   /**
*

Checks if a calendar date is after today and within a number of days in the future.

    * @param cal the calendar, not altered, not null
    * @param days the number of days.
    * @return true if the calendar date day is after today and within days in the future .
    * @throws IllegalArgumentException if the calendar is null
    */
   public static boolean isWithinDaysFuture(Calendar cal, int days) {
       if (cal == null) {
           throw new IllegalArgumentException("The date must not be null");
       }
       Calendar today = Calendar.getInstance();
       Calendar future = Calendar.getInstance();
       future.add(Calendar.DAY_OF_YEAR, days);
       return (isAfterDay(cal, today) && ! isAfterDay(cal, future));
   }
   
   /** Returns the given date with the time set to the start of the day. */
   public static Date getStart(Date date) {
       return clearTime(date);
   }
   
   /** Returns the given date with the time values cleared. */
   public static Date clearTime(Date date) {
       if (date == null) {
           return null;
       }
       Calendar c = Calendar.getInstance();
       c.setTime(date);
       c.set(Calendar.HOUR_OF_DAY, 0);
       c.set(Calendar.MINUTE, 0);
       c.set(Calendar.SECOND, 0);
       c.set(Calendar.MILLISECOND, 0);
       return c.getTime();
   }    
   /** Determines whether or not a date has any time values (hour, minute, 
    * seconds or millisecondsReturns the given date with the time values cleared. */
   /**
    * Determines whether or not a date has any time values.
    * @param date The date.
    * @return true iff the date is not null and any of the date"s hour, minute,
    * seconds or millisecond values are greater than zero.
    */
   public static boolean hasTime(Date date) {
       if (date == null) {
           return false;
       }
       Calendar c = Calendar.getInstance();
       c.setTime(date);
       if (c.get(Calendar.HOUR_OF_DAY) > 0) {
           return true;
       }
       if (c.get(Calendar.MINUTE) > 0) {
           return true;
       }
       if (c.get(Calendar.SECOND) > 0) {
           return true;
       }
       if (c.get(Calendar.MILLISECOND) > 0) {
           return true;
       }
       return false;
   }
   /** Returns the given date with time set to the end of the day */
   public static Date getEnd(Date date) {
       if (date == null) {
           return null;
       }
       Calendar c = Calendar.getInstance();
       c.setTime(date);
       c.set(Calendar.HOUR_OF_DAY, 23);
       c.set(Calendar.MINUTE, 59);
       c.set(Calendar.SECOND, 59);
       c.set(Calendar.MILLISECOND, 999);
       return c.getTime();
   }
   /** 
    * Returns the maximum of two dates. A null date is treated as being less
    * than any non-null date. 
    */
   public static Date max(Date d1, Date d2) {
       if (d1 == null && d2 == null) return null;
       if (d1 == null) return d2;
       if (d2 == null) return d1;
       return (d1.after(d2)) ? d1 : d2;
   }
   
   /** 
    * Returns the minimum of two dates. A null date is treated as being greater
    * than any non-null date. 
    */
   public static Date min(Date d1, Date d2) {
       if (d1 == null && d2 == null) return null;
       if (d1 == null) return d2;
       if (d2 == null) return d1;
       return (d1.before(d2)) ? d1 : d2;
   }
   /** The maximum date possible. */
   public static Date MAX_DATE = new Date(Long.MAX_VALUE);
   

}


 </source>
   
  
 
  



Checks if two calendars represent the same day ignoring time

   <source lang="java">
  

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

   /**
*

Checks if two dates are on the same day ignoring time.

    * @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
    */
   public static boolean isSameDay(Date date1, Date date2) {
       if (date1 == null || date2 == null) {
           throw new IllegalArgumentException("The dates 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 calendars represent the same day ignoring time.

    * @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
    */
   public static boolean isSameDay(Calendar cal1, Calendar cal2) {
       if (cal1 == null || cal2 == null) {
           throw new IllegalArgumentException("The dates 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));
   }
   
   /**
*

Checks if a date is today.

    * @param date the date, not altered, not null.
    * @return true if the date is today.
    * @throws IllegalArgumentException if the date is null
    */
   public static boolean isToday(Date date) {
       return isSameDay(date, Calendar.getInstance().getTime());
   }
   
   /**
*

Checks if a calendar date is today.

    * @param cal  the calendar, not altered, not null
    * @return true if cal date is today
    * @throws IllegalArgumentException if the calendar is null
    */
   public static boolean isToday(Calendar cal) {
       return isSameDay(cal, Calendar.getInstance());
   }
   
   /**
*

Checks if the first date is before the second date ignoring time.

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

Checks if the first calendar date is before the second calendar date ignoring time.

    * @param cal1 the first calendar, not altered, not null.
    * @param cal2 the second calendar, not altered, not null.
    * @return true if cal1 date is before cal2 date ignoring time.
    * @throws IllegalArgumentException if either of the calendars are null
    */
   public static boolean isBeforeDay(Calendar cal1, Calendar cal2) {
       if (cal1 == null || cal2 == null) {
           throw new IllegalArgumentException("The dates must not be null");
       }
       if (cal1.get(Calendar.ERA) < cal2.get(Calendar.ERA)) return true;
       if (cal1.get(Calendar.ERA) > cal2.get(Calendar.ERA)) return false;
       if (cal1.get(Calendar.YEAR) < cal2.get(Calendar.YEAR)) return true;
       if (cal1.get(Calendar.YEAR) > cal2.get(Calendar.YEAR)) return false;
       return cal1.get(Calendar.DAY_OF_YEAR) < cal2.get(Calendar.DAY_OF_YEAR);
   }
   
   /**
*

Checks if the first date is after the second date ignoring time.

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

Checks if the first calendar date is after the second calendar date ignoring time.

    * @param cal1 the first calendar, not altered, not null.
    * @param cal2 the second calendar, not altered, not null.
    * @return true if cal1 date is after cal2 date ignoring time.
    * @throws IllegalArgumentException if either of the calendars are null
    */
   public static boolean isAfterDay(Calendar cal1, Calendar cal2) {
       if (cal1 == null || cal2 == null) {
           throw new IllegalArgumentException("The dates must not be null");
       }
       if (cal1.get(Calendar.ERA) < cal2.get(Calendar.ERA)) return false;
       if (cal1.get(Calendar.ERA) > cal2.get(Calendar.ERA)) return true;
       if (cal1.get(Calendar.YEAR) < cal2.get(Calendar.YEAR)) return false;
       if (cal1.get(Calendar.YEAR) > cal2.get(Calendar.YEAR)) return true;
       return cal1.get(Calendar.DAY_OF_YEAR) > cal2.get(Calendar.DAY_OF_YEAR);
   }
   
   /**
*

Checks if a date is after today and within a number of days in the future.

    * @param date the date to check, not altered, not null.
    * @param days the number of days.
    * @return true if the date day is after today and within days in the future .
    * @throws IllegalArgumentException if the date is null
    */
   public static boolean isWithinDaysFuture(Date date, int days) {
       if (date == null) {
           throw new IllegalArgumentException("The date must not be null");
       }
       Calendar cal = Calendar.getInstance();
       cal.setTime(date);
       return isWithinDaysFuture(cal, days);
   }
   
   /**
*

Checks if a calendar date is after today and within a number of days in the future.

    * @param cal the calendar, not altered, not null
    * @param days the number of days.
    * @return true if the calendar date day is after today and within days in the future .
    * @throws IllegalArgumentException if the calendar is null
    */
   public static boolean isWithinDaysFuture(Calendar cal, int days) {
       if (cal == null) {
           throw new IllegalArgumentException("The date must not be null");
       }
       Calendar today = Calendar.getInstance();
       Calendar future = Calendar.getInstance();
       future.add(Calendar.DAY_OF_YEAR, days);
       return (isAfterDay(cal, today) && ! isAfterDay(cal, future));
   }
   
   /** Returns the given date with the time set to the start of the day. */
   public static Date getStart(Date date) {
       return clearTime(date);
   }
   
   /** Returns the given date with the time values cleared. */
   public static Date clearTime(Date date) {
       if (date == null) {
           return null;
       }
       Calendar c = Calendar.getInstance();
       c.setTime(date);
       c.set(Calendar.HOUR_OF_DAY, 0);
       c.set(Calendar.MINUTE, 0);
       c.set(Calendar.SECOND, 0);
       c.set(Calendar.MILLISECOND, 0);
       return c.getTime();
   }    
   /** Determines whether or not a date has any time values (hour, minute, 
    * seconds or millisecondsReturns the given date with the time values cleared. */
   /**
    * Determines whether or not a date has any time values.
    * @param date The date.
    * @return true iff the date is not null and any of the date"s hour, minute,
    * seconds or millisecond values are greater than zero.
    */
   public static boolean hasTime(Date date) {
       if (date == null) {
           return false;
       }
       Calendar c = Calendar.getInstance();
       c.setTime(date);
       if (c.get(Calendar.HOUR_OF_DAY) > 0) {
           return true;
       }
       if (c.get(Calendar.MINUTE) > 0) {
           return true;
       }
       if (c.get(Calendar.SECOND) > 0) {
           return true;
       }
       if (c.get(Calendar.MILLISECOND) > 0) {
           return true;
       }
       return false;
   }
   /** Returns the given date with time set to the end of the day */
   public static Date getEnd(Date date) {
       if (date == null) {
           return null;
       }
       Calendar c = Calendar.getInstance();
       c.setTime(date);
       c.set(Calendar.HOUR_OF_DAY, 23);
       c.set(Calendar.MINUTE, 59);
       c.set(Calendar.SECOND, 59);
       c.set(Calendar.MILLISECOND, 999);
       return c.getTime();
   }
   /** 
    * Returns the maximum of two dates. A null date is treated as being less
    * than any non-null date. 
    */
   public static Date max(Date d1, Date d2) {
       if (d1 == null && d2 == null) return null;
       if (d1 == null) return d2;
       if (d2 == null) return d1;
       return (d1.after(d2)) ? d1 : d2;
   }
   
   /** 
    * Returns the minimum of two dates. A null date is treated as being greater
    * than any non-null date. 
    */
   public static Date min(Date d1, Date d2) {
       if (d1 == null && d2 == null) return null;
       if (d1 == null) return d2;
       if (d2 == null) return d1;
       return (d1.before(d2)) ? d1 : d2;
   }
   /** The maximum date possible. */
   public static Date MAX_DATE = new Date(Long.MAX_VALUE);
   

}


 </source>
   
  
 
  



Checks if two dates are on the same day ignoring time

   <source lang="java">
  

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

* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the License). You may not use this file except in
* compliance with the License.
*
* You can get a copy of the License at http://www.thinkingrock.ru.au/cddl.html
* or http://www.thinkingrock.ru.au/cddl.txt.
*
* When distributing Covered Code, include this CDDL Header Notice in each file
* and include the License file at http://www.thinkingrock.ru.au/cddl.txt.
* If applicable, add the following below the CDDL Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* The Original Software is ThinkingRock. The Initial Developer of the Original
* Software is Avente Pty Ltd, Australia.
*
* Portions Copyright 2006-2007 Avente Pty Ltd. All Rights Reserved.
*/

public class Util {

 /**
*

Checks if two dates are on the same day ignoring time.

  * @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
  */
 public static boolean isSameDay(Date date1, Date date2) {
     if (date1 == null || date2 == null) {
         throw new IllegalArgumentException("The dates must not be null");
     }
     Calendar cal1 = Calendar.getInstance();
     cal1.setTime(date1);
     Calendar cal2 = Calendar.getInstance();
     cal2.setTime(date2);
     return isSameDay(cal1, cal2);
 }

}


 </source>
   
  
 
  



Checks the day, month and year are equal

   <source lang="java">
  

/*

* Copyright Javelin Software, All rights reserved.
*/

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

* The DateUtil is used as a Utility Class for Dates.
* 
* @author Robin Sharp
*/

public class DateUtil {

   public final static long SECOND_MILLIS = 1000;
   public final static long MINUTE_MILLIS = SECOND_MILLIS*60;
   public final static long HOUR_MILLIS = MINUTE_MILLIS*60;
   public final static long DAY_MILLIS = HOUR_MILLIS*24;
   public final static long YEAR_MILLIS = DAY_MILLIS*365;
   public static DateFormat OUT_DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy");
   public static DateFormat OUT_TIME_FORMAT = new SimpleDateFormat("H:mm:ss");
   public static DateFormat OUT_DATETIME_FORMAT = new SimpleDateFormat("d/M/yyyy H:mm:ss");
   public static DateFormat OUT_TIMESTAMP_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss.SSS");
   
   public static DateFormat IN_DATE_FORMAT = new SimpleDateFormat("d/M/yy");
   public static DateFormat IN_TIME_FORMAT = new SimpleDateFormat("H:mm:ss");
   public static DateFormat IN_DATETIME_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss");
   public static DateFormat IN_TIMESTAMP_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss.SSS");
   
   public static DateFormat DATE_TIME_FORMAT= new SimpleDateFormat( "yyyyMMddkkmmss" );  
   public static Calendar calendar = new GregorianCalendar();
   static
   {
       IN_DATE_FORMAT.setLenient(false);
       IN_TIME_FORMAT.setLenient(false);
       IN_DATETIME_FORMAT.setLenient(false);
   }
   /**
    * Create a new DateTime. To the last second. This will not create any 
    * extra-millis-seconds, which may cause bugs when writing to stores such as
    * databases that round milli-seconds up and down. 
    */
   public static java.util.Date newDateTime()
   {
       return new java.util.Date( (System.currentTimeMillis()/SECOND_MILLIS)*SECOND_MILLIS);
   }
   /**
    * Create a new Date. To the last day.
    */
   public static java.sql.Date newDate()
   {
       return new java.sql.Date( (System.currentTimeMillis()/DAY_MILLIS)*DAY_MILLIS);
   }
   
   /**
    * Create a new Time, with no date component. 
    */
   public static java.sql.Time newTime()
   {
       return new java.sql.Time( System.currentTimeMillis()%DAY_MILLIS);
   }
   
   /**
    * Create a new Timestamp. 
    */
   public static java.sql.Timestamp newTimestamp()
   {
       return new java.sql.Timestamp( System.currentTimeMillis() );
   }
   
   /**
    * Get the seconds difference
    */
   public static int secondsDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/SECOND_MILLIS) - (earlierDate.getTime()/SECOND_MILLIS));
   }
   /**
    * Get the minutes difference
    */
   public static int minutesDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/MINUTE_MILLIS) - (earlierDate.getTime()/MINUTE_MILLIS));
   }
   
   /**
    * Get the hours difference
    */
   public static int hoursDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/HOUR_MILLIS) - (earlierDate.getTime()/HOUR_MILLIS));
   }
   
   /**
    * Get the days difference
    */
   public static int daysDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/DAY_MILLIS) - (earlierDate.getTime()/DAY_MILLIS));
   }
   
  /**
   * Roll the java.util.Time forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.sql.Time rollTime( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.sql.Time(gc.getTime().getTime());
   }
   
  /**
   * Roll the java.util.Date forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.util.Date rollDateTime( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.util.Date(gc.getTime().getTime());
   }
   
  /**
   * Roll the java.sql.Date forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.sql.Date rollDate( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.sql.Date(gc.getTime().getTime());
   }
   
  /**
   * Roll the years forward or backward.
   * @param startDate - The start date
   * @param years - Negative to rollbackwards.
   */
   public static java.sql.Date rollYears( java.util.Date startDate, int years )
   {
       return rollDate( startDate, Calendar.YEAR, years );
   }
  /**
   * Roll the days forward or backward.
   * @param startDate - The start date
   * @param months - Negative to rollbackwards.
   */
   public static java.sql.Date rollMonths( java.util.Date startDate, int months )
   {
       return rollDate( startDate, Calendar.MONTH, months );
   }
  /**
   * Roll the days forward or backward.
   * @param startDate - The start date
   * @param days - Negative to rollbackwards.
   */
   public static java.sql.Date rollDays( java.util.Date startDate, int days )
   {
       return rollDate( startDate, Calendar.DATE, days );
   }
   
    /**
     * Checks the day, month and year are equal.
     */
    public static boolean dateEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;
       
       return d1.getDate() == d2.getDate() &&
              d1.getMonth() == d2.getMonth() &&
              d1.getYear() == d2.getYear();
    }
    
    /**
     * Checks the hour, minute and second are equal.
     */
    public static boolean timeEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;
       
       return d1.getHours() == d2.getHours() &&
              d1.getMinutes() == d2.getMinutes() &&
              d1.getSeconds() == d2.getSeconds();
    }
   /**
     * Checks the second, hour, month, day, month and year are equal.
     */
    public static boolean dateTimeEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;               
       
       return d1.getDate() == d2.getDate() &&
              d1.getMonth() == d2.getMonth() &&
              d1.getYear() == d2.getYear() &&
              d1.getHours() == d2.getHours() &&
              d1.getMinutes() == d2.getMinutes() &&
              d1.getSeconds() == d2.getSeconds();
    }
    
    /**
    * Convert an Object of type Classs to an Object.
    */
   public static Object toObject( Class clazz, Object value ) throws ParseException
   {
       if( value == null ) return null;
       if( clazz == null ) return value;
       
       if( java.sql.Date.class.isAssignableFrom( clazz ) ) return toDate( value );
       if( java.sql.Time.class.isAssignableFrom( clazz ) ) return toTime( value );
       if( java.sql.Timestamp.class.isAssignableFrom( clazz ) ) return toTimestamp( value );
       if( java.util.Date.class.isAssignableFrom( clazz ) ) return toDateTime( value );
       
       return value;
   }
   
   /**
    * Convert an Object to a DateTime, without an Exception
    */
   public static java.util.Date getDateTime( Object value )
   {
       try
       {
           return toDateTime( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   
   /**
    * Convert an Object to a DateTime.
    */
   public static java.util.Date toDateTime( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.util.Date ) return (java.util.Date)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return IN_DATETIME_FORMAT.parse( (String)value );
       }
               
       return IN_DATETIME_FORMAT.parse( value.toString() );
   }
   
   /**
    * Convert an Object to a Date, without an Exception
    */
   public static java.sql.Date getDate( Object value )
   {
       try
       {
           return toDate( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   /**
    * Convert an Object to a Date.
    */
   public static java.sql.Date toDate( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Date ) return (java.sql.Date)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Date( IN_DATE_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Date( IN_DATE_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Convert an Object to a Time, without an Exception
    */
   public static java.sql.Time getTime( Object value )
   {
       try
       {
           return toTime( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   
   /**
    * Convert an Object to a Time.
    */
   public static java.sql.Time toTime( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Time ) return (java.sql.Time)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Time( IN_TIME_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Time( IN_TIME_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Convert an Object to a Timestamp, without an Exception
    */
   public static java.sql.Timestamp getTimestamp( Object value )
   {
       try
       {
           return toTimestamp( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   /**
    * Convert an Object to a Timestamp.
    */
   public static java.sql.Timestamp toTimestamp( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Timestamp ) return (java.sql.Timestamp)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Timestamp( IN_TIMESTAMP_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Timestamp( IN_TIMESTAMP_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Tells you if the date part of a datetime is in a certain time range.
    */
   public static boolean isTimeInRange( java.sql.Time start, java.sql.Time end, java.util.Date d )
   {
       d=new java.sql.Time(d.getHours(),d.getMinutes(),d.getSeconds());
       
       if (start==null || end==null)
       {
           return false;
       }
       
       if (start.before(end)&&(!(d.after(start)&&d.before(end))))
       {
           return false;
       }
       
       if (end.before(start)&&(!(d.after(end)||d.before(start))))
       {
           return false;
       }   
       return true;
   }
   public static  int getYear( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.YEAR );
   }
   public static int getMonth( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MONTH );
   }
   public static int getDate( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.DATE );
   }
   public static int getHour( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.HOUR );
   }
   public static int getMinute( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MINUTE );
   }
   public static int getSeconds( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.SECOND );
   }
   public static int getMillisecond( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MILLISECOND );
   }
   
   /**
    * Convert an Object to a String using Dates
    */
   public static String toString( Object date )
   {
       if( date == null ) return null;
       
       if( java.sql.Timestamp.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_TIMESTAMP_FORMAT.format( date );
       }
       if( java.sql.Time.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_TIME_FORMAT.format( date );
       }
       if( java.sql.Date.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_DATE_FORMAT.format( date );
       }
       if( java.util.Date.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_DATETIME_FORMAT.format( date );
       }
       
       throw new IllegalArgumentException( "Unsupported type " + date.getClass() );
   }

}


 </source>
   
  
 
  



Checks the hour, minute and second are equal

   <source lang="java">
  

/*

* Copyright Javelin Software, All rights reserved.
*/

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

* The DateUtil is used as a Utility Class for Dates.
* 
* @author Robin Sharp
*/

public class DateUtil {

   public final static long SECOND_MILLIS = 1000;
   public final static long MINUTE_MILLIS = SECOND_MILLIS*60;
   public final static long HOUR_MILLIS = MINUTE_MILLIS*60;
   public final static long DAY_MILLIS = HOUR_MILLIS*24;
   public final static long YEAR_MILLIS = DAY_MILLIS*365;
   public static DateFormat OUT_DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy");
   public static DateFormat OUT_TIME_FORMAT = new SimpleDateFormat("H:mm:ss");
   public static DateFormat OUT_DATETIME_FORMAT = new SimpleDateFormat("d/M/yyyy H:mm:ss");
   public static DateFormat OUT_TIMESTAMP_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss.SSS");
   
   public static DateFormat IN_DATE_FORMAT = new SimpleDateFormat("d/M/yy");
   public static DateFormat IN_TIME_FORMAT = new SimpleDateFormat("H:mm:ss");
   public static DateFormat IN_DATETIME_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss");
   public static DateFormat IN_TIMESTAMP_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss.SSS");
   
   public static DateFormat DATE_TIME_FORMAT= new SimpleDateFormat( "yyyyMMddkkmmss" );  
   public static Calendar calendar = new GregorianCalendar();
   static
   {
       IN_DATE_FORMAT.setLenient(false);
       IN_TIME_FORMAT.setLenient(false);
       IN_DATETIME_FORMAT.setLenient(false);
   }
   /**
    * Create a new DateTime. To the last second. This will not create any 
    * extra-millis-seconds, which may cause bugs when writing to stores such as
    * databases that round milli-seconds up and down. 
    */
   public static java.util.Date newDateTime()
   {
       return new java.util.Date( (System.currentTimeMillis()/SECOND_MILLIS)*SECOND_MILLIS);
   }
   /**
    * Create a new Date. To the last day.
    */
   public static java.sql.Date newDate()
   {
       return new java.sql.Date( (System.currentTimeMillis()/DAY_MILLIS)*DAY_MILLIS);
   }
   
   /**
    * Create a new Time, with no date component. 
    */
   public static java.sql.Time newTime()
   {
       return new java.sql.Time( System.currentTimeMillis()%DAY_MILLIS);
   }
   
   /**
    * Create a new Timestamp. 
    */
   public static java.sql.Timestamp newTimestamp()
   {
       return new java.sql.Timestamp( System.currentTimeMillis() );
   }
   
   /**
    * Get the seconds difference
    */
   public static int secondsDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/SECOND_MILLIS) - (earlierDate.getTime()/SECOND_MILLIS));
   }
   /**
    * Get the minutes difference
    */
   public static int minutesDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/MINUTE_MILLIS) - (earlierDate.getTime()/MINUTE_MILLIS));
   }
   
   /**
    * Get the hours difference
    */
   public static int hoursDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/HOUR_MILLIS) - (earlierDate.getTime()/HOUR_MILLIS));
   }
   
   /**
    * Get the days difference
    */
   public static int daysDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/DAY_MILLIS) - (earlierDate.getTime()/DAY_MILLIS));
   }
   
  /**
   * Roll the java.util.Time forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.sql.Time rollTime( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.sql.Time(gc.getTime().getTime());
   }
   
  /**
   * Roll the java.util.Date forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.util.Date rollDateTime( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.util.Date(gc.getTime().getTime());
   }
   
  /**
   * Roll the java.sql.Date forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.sql.Date rollDate( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.sql.Date(gc.getTime().getTime());
   }
   
  /**
   * Roll the years forward or backward.
   * @param startDate - The start date
   * @param years - Negative to rollbackwards.
   */
   public static java.sql.Date rollYears( java.util.Date startDate, int years )
   {
       return rollDate( startDate, Calendar.YEAR, years );
   }
  /**
   * Roll the days forward or backward.
   * @param startDate - The start date
   * @param months - Negative to rollbackwards.
   */
   public static java.sql.Date rollMonths( java.util.Date startDate, int months )
   {
       return rollDate( startDate, Calendar.MONTH, months );
   }
  /**
   * Roll the days forward or backward.
   * @param startDate - The start date
   * @param days - Negative to rollbackwards.
   */
   public static java.sql.Date rollDays( java.util.Date startDate, int days )
   {
       return rollDate( startDate, Calendar.DATE, days );
   }
   
    /**
     * Checks the day, month and year are equal.
     */
    public static boolean dateEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;
       
       return d1.getDate() == d2.getDate() &&
              d1.getMonth() == d2.getMonth() &&
              d1.getYear() == d2.getYear();
    }
    
    /**
     * Checks the hour, minute and second are equal.
     */
    public static boolean timeEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;
       
       return d1.getHours() == d2.getHours() &&
              d1.getMinutes() == d2.getMinutes() &&
              d1.getSeconds() == d2.getSeconds();
    }
   /**
     * Checks the second, hour, month, day, month and year are equal.
     */
    public static boolean dateTimeEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;               
       
       return d1.getDate() == d2.getDate() &&
              d1.getMonth() == d2.getMonth() &&
              d1.getYear() == d2.getYear() &&
              d1.getHours() == d2.getHours() &&
              d1.getMinutes() == d2.getMinutes() &&
              d1.getSeconds() == d2.getSeconds();
    }
    
    /**
    * Convert an Object of type Classs to an Object.
    */
   public static Object toObject( Class clazz, Object value ) throws ParseException
   {
       if( value == null ) return null;
       if( clazz == null ) return value;
       
       if( java.sql.Date.class.isAssignableFrom( clazz ) ) return toDate( value );
       if( java.sql.Time.class.isAssignableFrom( clazz ) ) return toTime( value );
       if( java.sql.Timestamp.class.isAssignableFrom( clazz ) ) return toTimestamp( value );
       if( java.util.Date.class.isAssignableFrom( clazz ) ) return toDateTime( value );
       
       return value;
   }
   
   /**
    * Convert an Object to a DateTime, without an Exception
    */
   public static java.util.Date getDateTime( Object value )
   {
       try
       {
           return toDateTime( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   
   /**
    * Convert an Object to a DateTime.
    */
   public static java.util.Date toDateTime( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.util.Date ) return (java.util.Date)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return IN_DATETIME_FORMAT.parse( (String)value );
       }
               
       return IN_DATETIME_FORMAT.parse( value.toString() );
   }
   
   /**
    * Convert an Object to a Date, without an Exception
    */
   public static java.sql.Date getDate( Object value )
   {
       try
       {
           return toDate( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   /**
    * Convert an Object to a Date.
    */
   public static java.sql.Date toDate( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Date ) return (java.sql.Date)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Date( IN_DATE_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Date( IN_DATE_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Convert an Object to a Time, without an Exception
    */
   public static java.sql.Time getTime( Object value )
   {
       try
       {
           return toTime( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   
   /**
    * Convert an Object to a Time.
    */
   public static java.sql.Time toTime( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Time ) return (java.sql.Time)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Time( IN_TIME_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Time( IN_TIME_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Convert an Object to a Timestamp, without an Exception
    */
   public static java.sql.Timestamp getTimestamp( Object value )
   {
       try
       {
           return toTimestamp( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   /**
    * Convert an Object to a Timestamp.
    */
   public static java.sql.Timestamp toTimestamp( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Timestamp ) return (java.sql.Timestamp)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Timestamp( IN_TIMESTAMP_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Timestamp( IN_TIMESTAMP_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Tells you if the date part of a datetime is in a certain time range.
    */
   public static boolean isTimeInRange( java.sql.Time start, java.sql.Time end, java.util.Date d )
   {
       d=new java.sql.Time(d.getHours(),d.getMinutes(),d.getSeconds());
       
       if (start==null || end==null)
       {
           return false;
       }
       
       if (start.before(end)&&(!(d.after(start)&&d.before(end))))
       {
           return false;
       }
       
       if (end.before(start)&&(!(d.after(end)||d.before(start))))
       {
           return false;
       }   
       return true;
   }
   public static  int getYear( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.YEAR );
   }
   public static int getMonth( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MONTH );
   }
   public static int getDate( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.DATE );
   }
   public static int getHour( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.HOUR );
   }
   public static int getMinute( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MINUTE );
   }
   public static int getSeconds( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.SECOND );
   }
   public static int getMillisecond( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MILLISECOND );
   }
   
   /**
    * Convert an Object to a String using Dates
    */
   public static String toString( Object date )
   {
       if( date == null ) return null;
       
       if( java.sql.Timestamp.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_TIMESTAMP_FORMAT.format( date );
       }
       if( java.sql.Time.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_TIME_FORMAT.format( date );
       }
       if( java.sql.Date.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_DATE_FORMAT.format( date );
       }
       if( java.util.Date.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_DATETIME_FORMAT.format( date );
       }
       
       throw new IllegalArgumentException( "Unsupported type " + date.getClass() );
   }

}


 </source>
   
  
 
  



Compare two dates

   <source lang="java">
 

/**

* Copyright (c) 2003 - 2007 OpenSubsystems s.r.o. Slovak Republic. All rights reserved.
* 
* Project: OpenSubsystems
* 
* $Id: DateUtils.java,v 1.7 2007/01/07 06:14:00 bastafidli Exp $
* 
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License. 
* 
* 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 General Public License for more details.
* 
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
*/

import java.sql.Timestamp; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar;

/**

* Collection of useful utilities to work with dates. 
* 
* @version $Id: DateUtils.java,v 1.7 2007/01/07 06:14:00 bastafidli Exp $
* @author Miro Halas
* @code.reviewer Miro Halas
* @code.reviewed 1.5 2005/09/13 13:23:15 bastafidli
*/

public final class DateUtils {

  // Constants ////////////////////////////////////////////////////////////////
  
  /**
   * One second in milliseconds.
   */
  public static final long ONE_SECOND = 1000L;
  
  /**
   * One minute in milliseconds.
   */
  public static final long ONE_MINUTE = ONE_SECOND * 60L;
  
  /**
   * One hour in milliseconds.
   */
  public static final long ONE_HOUR = ONE_MINUTE * 60L;
  
  /**
   * One day in milliseconds.
   */
  public static final long ONE_DAY = ONE_HOUR * 24L;
  
  /**
   * Separator we used to separate time from the nanosecond portion of the 
   * timestamp when converted to string.
   */
  public static final char NANO_SEPARATOR = ":";
  
  /**
   * Constant for timing type
   */
  public static final int TIMING_NEVER = 0;
  /**
   * Constant for timing type
   */
  public static final int TIMING_MINUTES = 1;
  /**
   * Constant for timing type
   */
  public static final int TIMING_HOURS = 2;
  /**
   * Constant for timing type
   */
  public static final int TIMING_DAYS = 3;
  /**
   * Constant for timing type
   */
  public static final int TIMING_WEEKS = 4;
  /**
   * Constant for timing type
   */
  public static final int TIMING_MONTHS = 5;
  /**
   * Constant for timing type
   */
  public static final int TIMING_YEARS = 6;
  
  /**
   * Constant for timing type
   */
  public static final int TIMING_NONE = 7;
  /**
   * Constant for current date code used in date/time formulas 
   */
  public static final String CURRENT_DATE_CODE = "now";
  
  /**
   * Constant for dynamic date code used in date/time formulas
   */
  public static final char YEAR_CODE = "y";
  
  /**
   * Constant for dynamic date code used in date/time formulas
   */
  public static final char MONTH_CODE = "M";
  /**
   * Constant for dynamic date code used in date/time formulas
   */
  public static final char WEEK_CODE = "w";
  /**
   * Constant for dynamic date code used in date/time formulas
   */
  public static final char DAY_CODE = "d";
  /**
   * Constant for dynamic date code used in date/time formulas
   */
  public static final char HOUR_CODE = "h";
  /**
   * Constant for dynamic date code used in date/time formulas
   */
  public static final char MINUTE_CODE = "m";
  
  /**
   * Constant for dynamic date code used in date/time formulas
   */
  public static final char SECOND_CODE = "s";
  /**
   * constant for date type DATE
   */
  public static final int DATE_TYPE_DATE = 1;
  /**
   * constant for date type TIME
   */
  public static final int DATE_TYPE_TIME = 2;
  /**
   * constant for date type DATETIME
   */
  public static final int DATE_TYPE_DATETIME = 3;
  
  // Constants for period start types /////////////////////////////////////////

// TODO: For Miro: Remove this code once all the code which referred to these // constants was fixed // /** // * constant for period type // */ // public static final int PERIOD_START_TYPE_NONE = 0; // // /** // * constant for period type // */ // public static final int PERIOD_START_TYPE_CREATION = 1; // // /** // * constant for period type // */ // public static final int PERIOD_START_TYPE_COMPLETION = 2; // // /** // * constant for period type // */ // public static final int PERIOD_START_TYPE_APPROVAL = 3; // // /** // * constant for period type // */ // public static final int PERIOD_START_TYPE_ACTIVATION = 4; // // /** // * constant for period type // */ // public static final int PERIOD_START_TYPE_INACTIVATION = 5; // // /** // * constant for period type // */ // public static final int PERIOD_START_TYPE_DYNAMIC = 6; // // /** // * constant for period type code // */ // public static final int PERIOD_TYPE_CODE = 99; // // /** // * constant for period type object // */ // public static final Integer PERIOD_TYPE_OBJ = new Integer(PERIOD_TYPE_CODE);

  // Cached variables /////////////////////////////////////////////////////////
  
  /**
   * static SimpleDateFormat for date format to display on UI and in messages.
   */
  public static final SimpleDateFormat DATE_FORMAT 
                         = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT);
  
  /**
   * static SimpleDateFormat for time format to display on UI and in messages.
   */
  public static final SimpleDateFormat TIME_FORMAT 
                         = (SimpleDateFormat) DateFormat.getTimeInstance(DateFormat.MEDIUM);
  
  /**
   * static SimpleDateFormat for datetime format to display on UI and in messages.
   */
  public static final SimpleDateFormat DATETIME_FORMAT 
                         = (SimpleDateFormat) DateFormat.getDateTimeInstance(DateFormat.SHORT, 
                                                          DateFormat.MEDIUM); 
  /**
   * static SimpleDateFormat for date format to store date as string so that
   * it is stored consistently.
   */
  public static final SimpleDateFormat DATE_STORE_FORMAT
                         = new SimpleDateFormat("MM/dd/yyyy");
  
  /**
   * static SimpleDateFormat for time format to store time as string so that
   * it is stored consistently.
   */
  public static final SimpleDateFormat TIME_STORE_FORMAT 
                         = new SimpleDateFormat("HH:mm:ss");
  
  /**
   * static SimpleDateFormat for datetime format to store date and time as 
   * string so that it is stored consistently.
   */
  public static final SimpleDateFormat DATETIME_STORE_FORMAT 
                         = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
  /**
   * static SimpleDateFormat for date format for sql date
   */
  public static final SimpleDateFormat DATE_SQL_FORMAT
                         = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
  
  /**
   * static SimpleDateFormat for time format for sql time
   */
  public static final SimpleDateFormat TIME_SQL_FORMAT 
                         = new SimpleDateFormat("1970-01-01 HH:mm:ss");
  
  /**
   * static SimpleDateFormat for datetime format for sql date and time
   */
  public static final SimpleDateFormat DATETIME_SQL_FORMAT 
                         = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  // Constructors /////////////////////////////////////////////////////////////
  
  /** 
   * Private constructor since this class cannot be instantiated
   */
  private DateUtils(
  )
  {
     // Do nothing
  }
  
  // Public methods ///////////////////////////////////////////////////////////
  
  /**
   * Check if two dates equals regardless of the time. Two null dates are equal. 
   * Null and not null dates are not equal.
   * 
   * @param  dtFirst - first date to compare, can be null
   * @param  dtSecond - second date to compare, can be null 
   * @return boolean - true if two dates equals regardless of what the time is 
   */
  public static boolean dateEquals(
     Date dtFirst,
     Date dtSecond
  )
  {
     boolean  bReturn = false;
     
     // If they are the same object, they are equals
     bReturn = (dtFirst == dtSecond);
     if (!bReturn)
     {
        if (dtFirst == null)
        {
           // Two null dates are the same
           bReturn = (dtSecond == null);
        }
        else
        {
           if (dtSecond != null)
           {
              Calendar compCalendar;
              int      iEra;
              int      iYear;
              int      iMonth;
              int      iDay;
              
              compCalendar = Calendar.getInstance();
              compCalendar.setTime(dtFirst);
              iEra   = compCalendar.get(Calendar.ERA);
              iYear  = compCalendar.get(Calendar.YEAR);
              iMonth = compCalendar.get(Calendar.MONTH);
              iDay   = compCalendar.get(Calendar.DATE);
              compCalendar.setTime(dtSecond);
        
              bReturn = ((iEra == compCalendar.get(Calendar.ERA))
                        && (iYear == compCalendar.get(Calendar.YEAR))
                        && (iMonth == compCalendar.get(Calendar.MONTH))
                        && (iDay == compCalendar.get(Calendar.DATE)));
           }
        }
     } 
           
     return bReturn;            
  }
  
  /**
   * Check if two times equals regardless of the date. Two null times are equal. 
   * Null and not null times are not equal.
   * 
   * @param  dtFirst - first time to compare, can be null
   * @param  dtSecond - second time to compare, can be null
   * @param  bIgnoreMilliseconds - if true milliseconds will be ignored in comparison
   * @return boolean - true if two time equals regardless of what the date is 
   */
  public static boolean timeEquals(
     Date    dtFirst,
     Date    dtSecond,
     boolean bIgnoreMilliseconds
  )
  {
     boolean  bReturn = false;
     
     // If they are the same object, they are equals
     bReturn = (dtFirst == dtSecond);
     if (!bReturn)
     {
        if (dtFirst == null)
        {
           // Two null dates are the same
           bReturn = (dtSecond == null);
        }
        else
        {
           if (dtSecond != null)
           {
              Calendar compCalendar;
              int      iHour;
              int      iMinute;
              int      iSecond;
              int      iMili;
              
              compCalendar = Calendar.getInstance();
              compCalendar.setTime(dtFirst);
              iHour   = compCalendar.get(Calendar.HOUR_OF_DAY);
              iMinute = compCalendar.get(Calendar.MINUTE);
              iSecond = compCalendar.get(Calendar.SECOND);
              iMili   = compCalendar.get(Calendar.MILLISECOND);
              compCalendar.setTime(dtSecond);
        
              bReturn = ((iHour == compCalendar.get(Calendar.HOUR_OF_DAY))
                        && (iMinute == compCalendar.get(Calendar.MINUTE))
                        && (iSecond == compCalendar.get(Calendar.SECOND))
                        && ((bIgnoreMilliseconds) 
                           || (iMili == compCalendar.get(Calendar.MILLISECOND))));
           }
        }
     } 
           
     return bReturn;            
  }
  /**
   * Check if two dates and times are equal. Two null dates are equal. Null 
   * and not null dates are not equal.
   * 
   * @param  dtFirst - first date time to compare, can be null
   * @param  dtSecond - second date time to compare, can be null
   * @return boolean - true if two date and times are equal 
   */
  public static boolean dateAndTimeEquals(
     Date dtFirst,
     Date dtSecond
  )
  {
     boolean bReturn = false;
     
     // If they are the same object, they are equals
     bReturn = (dtFirst == dtSecond);
     if (!bReturn)
     {
        if (dtFirst == null)
        {
           // Two null dates are the same
           bReturn = (dtSecond == null);
        }
        else
        {
           if (dtSecond != null)
           {
              // They are both not null so they have to match to millisecond
              // (actually to nanosecond since the getTime takes nanoseconds
              // into account)
              bReturn = (dtFirst.getTime() == dtSecond.getTime());                               
           }
        }
     }
           
     return bReturn;            
  }
  /**
   * Check if String representing date is function or date. Date is a function
   * (formula) if it starts with the current date/time variable which can be 
   * followed by expression describing period from current date.
   *
   * @param strValue - string representation of date or date function
   * @return boolean - date function flag
   */
  public static boolean isFunction(
     String   strValue
  )
  {
     boolean bReturn = false;
     if ((strValue != null) && (strValue.length() > 0) 
        && (strValue.trim().startsWith(CURRENT_DATE_CODE)))
     {
        bReturn = true;
     }
     
     return bReturn;
  }
  
  /**
   * Parse date time value from given string resolving any functions or formulas
   * the string can contain. This method  can be therefore used if the passed 
   * string contains string representation date, time or timestamp or a formula
   * such as now + 3h - 1m + 4d. 
   *
   * @param strValue - string representation of date or date function
   * @param iDateType - date type code, one of the DATE_TYPE_XXX constants
   * @param stored - flag if Date should be parsed using format used for 
   *                 storage or for display
   * @return Timestamp - parsed date or null if date was null
   * @throws OSSInvalidDataException - error during parsing
   */
  public static Timestamp parseDateTime(
     String   strValue,
     int      iDateType,
     boolean  stored
  )
  {
     Timestamp tsReturn = null;
     Calendar workCal = GregorianCalendar.getInstance();
     
     if (strValue != null && strValue.length() > 0)
     {
        strValue = strValue.trim();
        if (strValue.startsWith(CURRENT_DATE_CODE))
        {
           strValue = strValue.replaceAll("[ ]", "");
           // If the user specified "UseCurrent", then substitute the
           // current date/time in the value
           workCal.setTime(new Date());

// Log.getInstance().debug("Parsing current date " + strValue);

           // Parse the date math
           int iBeginIndex = CURRENT_DATE_CODE.length();
           int iMaxLength = strValue.length();
           int iSign = 1;
           int iNumberIndex;
           int iValue;
           char cChar = " ";
           while (iBeginIndex < iMaxLength)
           {
              // This has to be sign
              if (strValue.charAt(iBeginIndex) == "+")
              {
                 iSign = 1;
              }
              else if (strValue.charAt(iBeginIndex) == "-")
              {
                 iSign = -1;
              }
              else
              {
                 // Incorrect String
                 throw new RuntimeException(
                          "Date function is in incorrect format: "
                          + strValue + " at " + strValue.substring(iBeginIndex));
              }
              iBeginIndex++;
              // Now we have to have number
              iNumberIndex = iBeginIndex;
              
              while (((iBeginIndex == iNumberIndex) || Character.isDigit(cChar)) 
                    && (iBeginIndex < iMaxLength))
              {
                 cChar = strValue.charAt(iBeginIndex++);
              }
              // We have to go one back because we should stop on modifier (e.g 1m)
              iBeginIndex--;
              try
              {
                 iValue = Integer.parseInt(strValue.substring(iNumberIndex, iBeginIndex));
              }
              catch (NumberFormatException nmeExc)
              {
                 // Incorrect String
                 throw new RuntimeException(
                          "Date function is in incorrect format: "
                          + strValue + " at " + strValue.substring(iNumberIndex));
              }
              // This has to be modifier: y - year, M - month, w - week, 
              // d - day, h - hour, m - minute, s - second
              cChar = strValue.charAt(iBeginIndex);
              switch(cChar)
              {
                 case(YEAR_CODE):
                 {
                    if (iDateType == DATE_TYPE_TIME)
                    {
                       throw new RuntimeException(
                          "Date function is in incorrect format: " +
                          "used YEAR modifier for TIME type");
                    }
                    workCal.add(Calendar.YEAR, iSign * iValue);
                    break;
                 }
                 case(MONTH_CODE):
                 {
                    if (iDateType == DATE_TYPE_TIME)
                    {
                       throw new RuntimeException(
                          "Date function is in incorrect format: " +
                          "used MONTH modifier for TIME type");
                    }
                    workCal.add(Calendar.MONTH, iSign * iValue);
                    break;
                 }
                 case(WEEK_CODE):
                 {
                    if (iDateType == DATE_TYPE_TIME)
                    {
                       throw new RuntimeException(
                          "Date function is in incorrect format: " +
                          "used WEEK modifier for TIME type");
                    }
                    workCal.add(Calendar.WEEK_OF_YEAR, iSign * iValue);
                    break;
                 }
                 case(DAY_CODE):
                 {
                    if (iDateType == DATE_TYPE_TIME)
                    {
                       throw new RuntimeException(
                          "Date function is in incorrect format: " +
                          "used DAY modifier for TIME type");
                    }
                    workCal.add(Calendar.DATE, iSign * iValue);
                    break;
                 }
                 case(HOUR_CODE):
                 {
                    if (iDateType == DATE_TYPE_DATE)
                    {
                       throw new RuntimeException(
                          "Date function is in incorrect format: " +
                          "used HOUR modifier for DATE type");
                    }
                    workCal.add(Calendar.HOUR, iSign * iValue);
                    break;
                 }
                 case(MINUTE_CODE):
                 {
                    if (iDateType == DATE_TYPE_DATE)
                    {
                       throw new RuntimeException(
                          "Date function is in incorrect format: " +
                          "used MINUTE modifier for DATE type");
                    }
                    workCal.add(Calendar.MINUTE, iSign * iValue);
                    break;
                 }
                 case(SECOND_CODE):
                 {
                    if (iDateType == DATE_TYPE_DATE)
                    {
                       throw new RuntimeException(
                          "Date function is in incorrect format: " +
                          "used SECOND modifier for DATE type");
                    }
                    workCal.add(Calendar.SECOND, iSign * iValue);
                    break;
                 }
                 default:
                 {
                    // Incorrect String
                    throw new RuntimeException(
                          "Date function is in incorrect format: "
                          + strValue + " at " + strValue.substring(iBeginIndex));
                 }
              }
              iBeginIndex++;
           }
           
           tsReturn = new Timestamp(workCal.getTimeInMillis());
           
        }
        else
        {
           try
           {
              if (stored)
              {
                 switch (iDateType)
                 {
                    case (DATE_TYPE_DATE) :
                    {
                       tsReturn = new Timestamp(DATE_STORE_FORMAT.parse(strValue).getTime());
                       break;   
                    }
                    case (DATE_TYPE_TIME) :
                    {
                       tsReturn = new Timestamp(TIME_STORE_FORMAT.parse(strValue).getTime());
                       break;   
                    }
                    case (DATE_TYPE_DATETIME) :
                    {
                       tsReturn = new Timestamp(DATETIME_STORE_FORMAT.parse(strValue).getTime());
                       break;   
                    }
                    default:
                    {
                       assert false : "Unknown date type " + iDateType;
                    }
                 }                  
              }
              else
              {
                 switch (iDateType)
                 {
                    case (DATE_TYPE_DATE) :
                    {
                       tsReturn = new Timestamp(DATE_FORMAT.parse(strValue).getTime());
                       break;   
                    }
                    case (DATE_TYPE_TIME) :
                    {
                       tsReturn = new Timestamp(TIME_FORMAT.parse(strValue).getTime());
                       break;   
                    }
                    case (DATE_TYPE_DATETIME) :
                    {
                       tsReturn = new Timestamp(DATETIME_FORMAT.parse(strValue).getTime());
                       break;   
                    }
                    default:
                    {
                       assert false : "Unknown date type " + iDateType;
                    }                  
                 }                  
              }
           }
           catch (ParseException peExc)
           {
              throw new RuntimeException(
                    "Date is in incorrect format. Problems with parsing.",
                    peExc);
           }
        }
     }
     return tsReturn;
  }
  
  /**
   * Parse the specified period into string displaying number of days the 
   * period represents. 
   * 
   * @param lPeriod - period in miliseconds
   * @return String - period in format "x day(s)" or "" if not valid period
   */
  public static String parseDayPeriod(
     long lPeriod
  )
  {
     StringBuffer sbReturn = new StringBuffer();
     long lDays = 0L;
     
     if (lPeriod > 0)
     {
        // we will count each started day as counted day 
        lPeriod = lPeriod + DateUtils.ONE_DAY - 1;
        
        lDays = lPeriod / DateUtils.ONE_DAY;
        sbReturn.append(lDays);
        if (lDays == 1L)
        {
           sbReturn.append(" day");
        }
        else
        {
           sbReturn.append(" days");
        }
     }
     else
     {
        sbReturn.append("0 days");
     }
     return sbReturn.toString();
  }
  
  /**
   * Parse the specified period into string displaying date and time the 
   * period represents. 
   * 
   * @param lPeriod - preiod in miliseconds
   * @return String - period in format "x day(s) y hour(s) z minute(s)" 
   *                  or "" if not valid period
   */
  public static String parseDayTimePeriod(
     long lPeriod
  )
  {
     StringBuffer sbReturn = new StringBuffer();
     long lHelp = 0L;
     
     
     if (lPeriod > 0)
     {
        lPeriod = lPeriod + DateUtils.ONE_MINUTE - 1;
        // we will count each started day as counted day 
        lHelp = lPeriod / DateUtils.ONE_DAY;
        if (lHelp > 0)
        {
           sbReturn.append(lHelp);
           if (lHelp == 1L)
           {
              sbReturn.append(" d ");
           }
           else
           {
              sbReturn.append(" d ");
           }
        }
        lPeriod = lPeriod % DateUtils.ONE_DAY;
        lHelp = lPeriod / DateUtils.ONE_HOUR;
        if (lHelp > 0 || sbReturn.length() > 0)
        {
           sbReturn.append(lHelp);
           if (lHelp == 1L)
           {
              sbReturn.append(" h ");
           }
           else
           {
              sbReturn.append(" h ");
           }
        }
        lPeriod = lPeriod % DateUtils.ONE_HOUR;
        lHelp = lPeriod / DateUtils.ONE_MINUTE;
        if (lHelp > 0 || sbReturn.length() > 0)
        {
           sbReturn.append(lHelp);
           if (lHelp == 1L)
           {
              sbReturn.append(" min");
           }
           else
           {
              sbReturn.append(" min");
           }
        }
     }
     else
     {
        sbReturn.append("0 min");
     }
     return sbReturn.toString();
  }
  

// TODO: For Miro: Remove this code once all the code which referred to these // was fixed. These should be moved to a GUI related class. // /** // * Method for list of timing types. // * // * @return List - list of timing types // */ // public static List getTimingTypes( // ) // { // List lstTimingTypes = new ArrayList(); // // lstTimingTypes.add(new SelectOption(Integer.toString(DateUtils.TIMING_MINUTES), // "Minute(s)")); // lstTimingTypes.add(new SelectOption(Integer.toString(DateUtils.TIMING_HOURS), "Hour(s)")); // lstTimingTypes.add(new SelectOption(Integer.toString(DateUtils.TIMING_DAYS), "Day(s)")); // lstTimingTypes.add(new SelectOption(Integer.toString(DateUtils.TIMING_WEEKS), "Week(s)")); // lstTimingTypes.add(new SelectOption(Integer.toString(DateUtils.TIMING_MONTHS), "Month(s)")); // lstTimingTypes.add(new SelectOption(Integer.toString(DateUtils.TIMING_YEARS), "Year(s)")); // lstTimingTypes.add(new SelectOption(Integer.toString(DateUtils.TIMING_NEVER), "Never")); // // return lstTimingTypes; // } // /** // * Method for list of timing types with None option. // * // * @return List - list of timing types // */ // public static List getTimingTypesWithNone( // ) // { // List lstTimingTypes = new ArrayList(); // // lstTimingTypes.add(new SelectOption(Integer.toString(DateUtils.TIMING_NONE), "None")); // lstTimingTypes.add(new SelectOption(Integer.toString(DateUtils.TIMING_MINUTES), // "Minute(s)")); // lstTimingTypes.add(new SelectOption(Integer.toString(DateUtils.TIMING_HOURS), "Hour(s)")); // lstTimingTypes.add(new SelectOption(Integer.toString(DateUtils.TIMING_DAYS), "Day(s)")); // lstTimingTypes.add(new SelectOption(Integer.toString(DateUtils.TIMING_WEEKS), "Week(s)")); // lstTimingTypes.add(new SelectOption(Integer.toString(DateUtils.TIMING_MONTHS), "Month(s)")); // lstTimingTypes.add(new SelectOption(Integer.toString(DateUtils.TIMING_YEARS), "Year(s)")); // lstTimingTypes.add(new SelectOption(Integer.toString(DateUtils.TIMING_NEVER), "Never")); // // return lstTimingTypes; // } // /** // * Method for getting string name of the timing type. // * // * @param iTimingType - timing type constant // * @return String - string name of timing type // */ // public static String getTimingTypeName( // int iTimingType // ) // { // String outTimingTypeName = "Never"; // switch (iTimingType) // { // case (DateUtils.TIMING_NEVER): // { // outTimingTypeName = "Never"; // break; // } // case (DateUtils.TIMING_MINUTES): // { // outTimingTypeName = "Minute(s)"; // break; // } // case (DateUtils.TIMING_HOURS): // { // outTimingTypeName = "Hour(s)"; // break; // } // case (DateUtils.TIMING_DAYS): // { // outTimingTypeName = "Day(s)"; // break; // } // case (DateUtils.TIMING_WEEKS): // { // outTimingTypeName = "Week(s)"; // break; // } // case (DateUtils.TIMING_MONTHS): // { // outTimingTypeName = "Month(s)"; // break; // } // case (DateUtils.TIMING_YEARS): // { // outTimingTypeName = "Year(s)"; // break; // } // case (DateUtils.TIMING_NONE): // { // outTimingTypeName = "None"; // break; // } // } // // return outTimingTypeName; // }

  /**
   * Get expiration timestamp from start date, period type and duration. For 
   * example if the start date is now, period type is hour and duration is 2
   * then the result will be timestamp representing now + 2 hours.  
   * 
   * @param tsStartDate - start date of period counting
   * @param iPeriodType - one of the period type constant TIMING_XXX 
   * @param iPeriodDuration - period duration, number of time units specified 
   *                          by period type
   * @return Timestamp - date of period expiration or null if any problem
   */
  public static Timestamp getPeriodExpiration(
     Timestamp tsStartDate,
     int       iPeriodType,
     int       iPeriodDuration
  )
  {
     Timestamp tsReturn = null;
     Calendar calHelp;
     if (tsStartDate != null && iPeriodDuration > 0 
           && iPeriodType > TIMING_NEVER && iPeriodType < TIMING_NONE)
     {
        calHelp = Calendar.getInstance();
        calHelp.setTime(tsStartDate);
        
        switch (iPeriodType)
        {
           case (TIMING_MINUTES) :
           {
              calHelp.add(Calendar.MINUTE, iPeriodDuration);
              break;
           }
           case (TIMING_HOURS) :
           {
              calHelp.add(Calendar.HOUR, iPeriodDuration);
              break;
           }
           case (TIMING_DAYS) :
           {
              calHelp.add(Calendar.DATE, iPeriodDuration);
              break;
           }
           case (TIMING_WEEKS) :
           {
              calHelp.add(Calendar.WEEK_OF_YEAR, iPeriodDuration);
              break;
           }
           case (TIMING_MONTHS) :
           {
              calHelp.add(Calendar.MONTH, iPeriodDuration);
              break;
           }
           case (TIMING_YEARS) :
           {
              calHelp.add(Calendar.YEAR, iPeriodDuration);
              break;
           }
           default :
           {
              assert false : "Not supported Timing type " + iPeriodType;
           } 
        }
        tsReturn = new Timestamp(calHelp.getTimeInMillis());
     }
     
     return tsReturn;
  }
  
  /**
   * Method to compare time periods
   * 
   * @param iPeriodType1 - first period type, one of the period type constant 
   *                       TIMING_XXX
   * @param iPeriodDuration1 - first period duration
   * @param iPeriodType2 - second period type, one of the period type constant 
   *                       TIMING_XXX
   * @param iPeriodDuration2 - second period duration
   * @return int - 1 - first period is longer
   *               0 - periods are same
   *              -1 - first period is shorter
   */
  public static int comparePeriods(
     int iPeriodType1,
     int iPeriodDuration1,
     int iPeriodType2,
     int iPeriodDuration2
  )
  {
     int iReturn = 0;
     
     if ((iPeriodType1 != TIMING_NEVER) && (iPeriodType1 != TIMING_NONE) 
        && (iPeriodType2 != TIMING_NEVER) && (iPeriodType2 != TIMING_NONE))
     {
        Timestamp tsTimestamp1 = getPeriodExpiration(
              new Timestamp(0), iPeriodType1, iPeriodDuration1);
        Timestamp tsTimestamp2 = getPeriodExpiration(
              new Timestamp(0), iPeriodType2, iPeriodDuration2);
        
        // TODO: Improve: When would any of these be null?
        if ((tsTimestamp1 != null) && (tsTimestamp2 != null))
        {
           if (tsTimestamp1.after(tsTimestamp2))
           {
              iReturn = 1;
           }
           else if (tsTimestamp2.after(tsTimestamp1))
           {
              iReturn = -1;
           }
        }
     }
     else
     {
        if (iPeriodType1 != iPeriodType2)
        {
           if (iPeriodType1 == TIMING_NEVER)
           {
              iReturn = 1;
           }
           else if (iPeriodType1 == TIMING_NONE)
           {
              iReturn = -1;
           }
           else if (iPeriodType2 == TIMING_NEVER)
           {
              iReturn = -1;
           }
           else if (iPeriodType2 == TIMING_NONE)
           {
              iReturn = 1;
           }
        }
     }
     return iReturn;      
  }
  
  /**
   * Convert timestamp to string including it"s nanosecond portion so that it 
   * can be safely stored in variable of web page.
   * 
   * @param tsTimestamp - timestamp to convert
   * @return String - text containing time and nanosecond portion of timestamp
   */
  public static String getTimestampAsString(
     Timestamp tsTimestamp
  )
  {
     StringBuffer sbTimestamp = new StringBuffer();
     
     sbTimestamp.append(tsTimestamp.getTime());
     sbTimestamp.append(NANO_SEPARATOR);
     sbTimestamp.append(tsTimestamp.getNanos());
     
     return sbTimestamp.toString();
  }
  
  /**
   * Function returns time string in the form MM:SS.MS from the input specified in miliseconds. 
   * 
   * @param lTimeInMiliseconds - time in miliseconds
   * @return String - string representation of miliseconds in the form MM:SS.MS
   */
  public static String getStringTime(
     long lTimeInMiliseconds
  )
  {
     long lTotalMS   = lTimeInMiliseconds;
     long lMS        = lTotalMS % 1000;
     long lTotalSecs = lTotalMS / 1000;
     long lSecs      = lTotalSecs % 60;
     long lTotalMins = lTotalSecs / 60;
     long lMinutes   = lTotalMins % 60;
     long lHours     = lTotalMins / 60;
     StringBuffer sbBuffer = new StringBuffer();
     if (lHours > 0)
     {
        sbBuffer.append(lHours);
        sbBuffer.append(":");
        sbBuffer.append(lMinutes);
        sbBuffer.append(":");
        sbBuffer.append(lSecs);
        sbBuffer.append(".");
        sbBuffer.append(lMS);
     }
     else if (lMinutes > 0)
     {
        sbBuffer.append(lMinutes);
        sbBuffer.append(":");
        sbBuffer.append(lSecs);
        sbBuffer.append(".");
        sbBuffer.append(lMS);
     }
     else if (lSecs > 0)
     {
        sbBuffer.append(lSecs);
        sbBuffer.append(".");
        sbBuffer.append(lMS);
        sbBuffer.append(" seconds");
     }
     else
     {
        sbBuffer.append(lMS);
        sbBuffer.append(" ms");
     }
     
     return sbBuffer.toString();
  }

// TODO: For Miro: Remove this code once all the code which referred to these // was fixed. These should be moved to a GUI or business logic related class. // /** // * Method to check if valid period settings // * // * @param iPeriod - period length // * @param iPeriodType - period type // * @param iPeriodStartType - period start type // * @param iAttributeId - attribute ID for dynamic period start type // * @param bPeriodException - period exception flag // * @param strPeriodName - period name used for exception message // * @param bAdvancePeriodType - flag if advanced period type (includes also start type) // * @param bfideException - invalid data exception // */ // public static void validatePeriod( // int iPeriod, // int iPeriodType, // int iPeriodStartType, // int iAttributeId, // boolean bPeriodException, // String strPeriodName, // boolean bAdvancePeriodType, // OSSInvalidDataException messageException // ) // { // if ((iPeriod > 0) // || ((iPeriodType != TIMING_NONE) && (iPeriodType != TIMING_NEVER)) // || (bPeriodException) || (iPeriodStartType != PERIOD_START_TYPE_NONE)) // { // if (iPeriod <= 0) // { // if (messageException == null) // { // messageException = new OSSInvalidDataException(); // } // messageException.getErrorMessages().addMessage( // PERIOD_TYPE_OBJ, // "You have to set valid period length for " + strPeriodName + " type." // ); // } // else if ((iPeriodType == TIMING_NONE) || (iPeriodType == TIMING_NEVER)) // { // if (messageException == null) // { // messageException = new OSSInvalidDataException(); // } // messageException.getErrorMessages().addMessage( // PERIOD_TYPE_OBJ, // "You have to set valid period type for " + strPeriodName + " type." // ); // } // else if ((bAdvancePeriodType) && (iPeriodStartType == PERIOD_START_TYPE_NONE)) // { // if (messageException == null) // { // messageException = new OSSInvalidDataException(); // } // messageException.getErrorMessages().addMessage( // PERIOD_TYPE_OBJ, // "You have to set valid period start type for " + strPeriodName + " type." // ); // } // else if ((bAdvancePeriodType) // && (iPeriodStartType == PERIOD_START_TYPE_DYNAMIC) // && (iAttributeId == DataObject.NEW_ID)) // { // if (messageException == null) // { // messageException = new OSSInvalidDataException(); // } // messageException.getErrorMessages().addMessage( // PERIOD_TYPE_OBJ, // "You have to set valid period dynamic start attribute for " // + strPeriodName + " type." // ); // } // } // } }


 </source>
   
  
 
  



Get the days difference

   <source lang="java">
  

/*

* Copyright Javelin Software, All rights reserved.
*/

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

* The DateUtil is used as a Utility Class for Dates.
* 
* @author Robin Sharp
*/

public class DateUtil {

   public final static long SECOND_MILLIS = 1000;
   public final static long MINUTE_MILLIS = SECOND_MILLIS*60;
   public final static long HOUR_MILLIS = MINUTE_MILLIS*60;
   public final static long DAY_MILLIS = HOUR_MILLIS*24;
   public final static long YEAR_MILLIS = DAY_MILLIS*365;
   public static DateFormat OUT_DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy");
   public static DateFormat OUT_TIME_FORMAT = new SimpleDateFormat("H:mm:ss");
   public static DateFormat OUT_DATETIME_FORMAT = new SimpleDateFormat("d/M/yyyy H:mm:ss");
   public static DateFormat OUT_TIMESTAMP_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss.SSS");
   
   public static DateFormat IN_DATE_FORMAT = new SimpleDateFormat("d/M/yy");
   public static DateFormat IN_TIME_FORMAT = new SimpleDateFormat("H:mm:ss");
   public static DateFormat IN_DATETIME_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss");
   public static DateFormat IN_TIMESTAMP_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss.SSS");
   
   public static DateFormat DATE_TIME_FORMAT= new SimpleDateFormat( "yyyyMMddkkmmss" );  
   public static Calendar calendar = new GregorianCalendar();
   static
   {
       IN_DATE_FORMAT.setLenient(false);
       IN_TIME_FORMAT.setLenient(false);
       IN_DATETIME_FORMAT.setLenient(false);
   }
   /**
    * Create a new DateTime. To the last second. This will not create any 
    * extra-millis-seconds, which may cause bugs when writing to stores such as
    * databases that round milli-seconds up and down. 
    */
   public static java.util.Date newDateTime()
   {
       return new java.util.Date( (System.currentTimeMillis()/SECOND_MILLIS)*SECOND_MILLIS);
   }
   /**
    * Create a new Date. To the last day.
    */
   public static java.sql.Date newDate()
   {
       return new java.sql.Date( (System.currentTimeMillis()/DAY_MILLIS)*DAY_MILLIS);
   }
   
   /**
    * Create a new Time, with no date component. 
    */
   public static java.sql.Time newTime()
   {
       return new java.sql.Time( System.currentTimeMillis()%DAY_MILLIS);
   }
   
   /**
    * Create a new Timestamp. 
    */
   public static java.sql.Timestamp newTimestamp()
   {
       return new java.sql.Timestamp( System.currentTimeMillis() );
   }
   
   /**
    * Get the seconds difference
    */
   public static int secondsDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/SECOND_MILLIS) - (earlierDate.getTime()/SECOND_MILLIS));
   }
   /**
    * Get the minutes difference
    */
   public static int minutesDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/MINUTE_MILLIS) - (earlierDate.getTime()/MINUTE_MILLIS));
   }
   
   /**
    * Get the hours difference
    */
   public static int hoursDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/HOUR_MILLIS) - (earlierDate.getTime()/HOUR_MILLIS));
   }
   
   /**
    * Get the days difference
    */
   public static int daysDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/DAY_MILLIS) - (earlierDate.getTime()/DAY_MILLIS));
   }
   
  /**
   * Roll the java.util.Time forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.sql.Time rollTime( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.sql.Time(gc.getTime().getTime());
   }
   
  /**
   * Roll the java.util.Date forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.util.Date rollDateTime( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.util.Date(gc.getTime().getTime());
   }
   
  /**
   * Roll the java.sql.Date forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.sql.Date rollDate( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.sql.Date(gc.getTime().getTime());
   }
   
  /**
   * Roll the years forward or backward.
   * @param startDate - The start date
   * @param years - Negative to rollbackwards.
   */
   public static java.sql.Date rollYears( java.util.Date startDate, int years )
   {
       return rollDate( startDate, Calendar.YEAR, years );
   }
  /**
   * Roll the days forward or backward.
   * @param startDate - The start date
   * @param months - Negative to rollbackwards.
   */
   public static java.sql.Date rollMonths( java.util.Date startDate, int months )
   {
       return rollDate( startDate, Calendar.MONTH, months );
   }
  /**
   * Roll the days forward or backward.
   * @param startDate - The start date
   * @param days - Negative to rollbackwards.
   */
   public static java.sql.Date rollDays( java.util.Date startDate, int days )
   {
       return rollDate( startDate, Calendar.DATE, days );
   }
   
    /**
     * Checks the day, month and year are equal.
     */
    public static boolean dateEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;
       
       return d1.getDate() == d2.getDate() &&
              d1.getMonth() == d2.getMonth() &&
              d1.getYear() == d2.getYear();
    }
    
    /**
     * Checks the hour, minute and second are equal.
     */
    public static boolean timeEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;
       
       return d1.getHours() == d2.getHours() &&
              d1.getMinutes() == d2.getMinutes() &&
              d1.getSeconds() == d2.getSeconds();
    }
   /**
     * Checks the second, hour, month, day, month and year are equal.
     */
    public static boolean dateTimeEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;               
       
       return d1.getDate() == d2.getDate() &&
              d1.getMonth() == d2.getMonth() &&
              d1.getYear() == d2.getYear() &&
              d1.getHours() == d2.getHours() &&
              d1.getMinutes() == d2.getMinutes() &&
              d1.getSeconds() == d2.getSeconds();
    }
    
    /**
    * Convert an Object of type Classs to an Object.
    */
   public static Object toObject( Class clazz, Object value ) throws ParseException
   {
       if( value == null ) return null;
       if( clazz == null ) return value;
       
       if( java.sql.Date.class.isAssignableFrom( clazz ) ) return toDate( value );
       if( java.sql.Time.class.isAssignableFrom( clazz ) ) return toTime( value );
       if( java.sql.Timestamp.class.isAssignableFrom( clazz ) ) return toTimestamp( value );
       if( java.util.Date.class.isAssignableFrom( clazz ) ) return toDateTime( value );
       
       return value;
   }
   
   /**
    * Convert an Object to a DateTime, without an Exception
    */
   public static java.util.Date getDateTime( Object value )
   {
       try
       {
           return toDateTime( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   
   /**
    * Convert an Object to a DateTime.
    */
   public static java.util.Date toDateTime( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.util.Date ) return (java.util.Date)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return IN_DATETIME_FORMAT.parse( (String)value );
       }
               
       return IN_DATETIME_FORMAT.parse( value.toString() );
   }
   
   /**
    * Convert an Object to a Date, without an Exception
    */
   public static java.sql.Date getDate( Object value )
   {
       try
       {
           return toDate( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   /**
    * Convert an Object to a Date.
    */
   public static java.sql.Date toDate( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Date ) return (java.sql.Date)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Date( IN_DATE_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Date( IN_DATE_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Convert an Object to a Time, without an Exception
    */
   public static java.sql.Time getTime( Object value )
   {
       try
       {
           return toTime( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   
   /**
    * Convert an Object to a Time.
    */
   public static java.sql.Time toTime( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Time ) return (java.sql.Time)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Time( IN_TIME_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Time( IN_TIME_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Convert an Object to a Timestamp, without an Exception
    */
   public static java.sql.Timestamp getTimestamp( Object value )
   {
       try
       {
           return toTimestamp( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   /**
    * Convert an Object to a Timestamp.
    */
   public static java.sql.Timestamp toTimestamp( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Timestamp ) return (java.sql.Timestamp)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Timestamp( IN_TIMESTAMP_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Timestamp( IN_TIMESTAMP_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Tells you if the date part of a datetime is in a certain time range.
    */
   public static boolean isTimeInRange( java.sql.Time start, java.sql.Time end, java.util.Date d )
   {
       d=new java.sql.Time(d.getHours(),d.getMinutes(),d.getSeconds());
       
       if (start==null || end==null)
       {
           return false;
       }
       
       if (start.before(end)&&(!(d.after(start)&&d.before(end))))
       {
           return false;
       }
       
       if (end.before(start)&&(!(d.after(end)||d.before(start))))
       {
           return false;
       }   
       return true;
   }
   public static  int getYear( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.YEAR );
   }
   public static int getMonth( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MONTH );
   }
   public static int getDate( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.DATE );
   }
   public static int getHour( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.HOUR );
   }
   public static int getMinute( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MINUTE );
   }
   public static int getSeconds( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.SECOND );
   }
   public static int getMillisecond( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MILLISECOND );
   }
   
   /**
    * Convert an Object to a String using Dates
    */
   public static String toString( Object date )
   {
       if( date == null ) return null;
       
       if( java.sql.Timestamp.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_TIMESTAMP_FORMAT.format( date );
       }
       if( java.sql.Time.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_TIME_FORMAT.format( date );
       }
       if( java.sql.Date.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_DATE_FORMAT.format( date );
       }
       if( java.util.Date.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_DATETIME_FORMAT.format( date );
       }
       
       throw new IllegalArgumentException( "Unsupported type " + date.getClass() );
   }

}


 </source>
   
  
 
  



Get the days passed from the specified date up to the date provided in the constructor

   <source lang="java">
  

/*

* Funambol is a mobile platform developed by Funambol, Inc. 
* Copyright (C) 2003 - 2007 Funambol, Inc.
* 
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission 
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE 
* WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
* 
* 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 General Public License for more
* details.
* 
* You should have received a copy of the GNU Affero General Public License 
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
* 
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite 
* 305, Redwood City, CA 94063, USA, or at email address info@funambol.ru.
* 
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
* 
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably 
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/

import java.util.Calendar; import java.util.Date; import java.util.TimeZone;

/**

* Utility class for date manipulation.
* This class gives a simple interface for common Date, Calendar and Timezone
* operations.
* It is possible to apply subsequent transformations to an initial date, and
* retrieve the changed Date object at any point.
*
*/

public class DateUtil {

   //-------------------------------------------------------------- Attributes
   private Calendar cal;
   
   //------------------------------------------------------------ Constructors
   
   /** Inizialize a new instance with the current date */
   public DateUtil() {
       this(new Date());
   }
   
   /** Inizialize a new instance with the given date */
   public DateUtil(Date d) {
       cal = Calendar.getInstance();
       cal.setTime(d);
   }
   
   //---------------------------------------------------------- Public methods
   
   /** Set a new time */
   public void setTime(Date d) {
       cal.setTime(d);
   }
   
   /** Get the current time */
   public Date getTime() {
       return cal.getTime();
   }
   
   /** Get the current TimeZone */
   public String getTZ() {
       return cal.getTimeZone().getID();
   }
   
   /**
    * Convert the time to the midnight of the currently set date.
    * The internal date is changed after this call.
    *
    * @return a reference to this DateUtil, for concatenation.
    */
   public DateUtil toMidnight() {
       
       cal.set(Calendar.HOUR_OF_DAY, 0);
       cal.set(Calendar.MINUTE, 0);
       cal.set(Calendar.SECOND, 0);
       cal.set(Calendar.MILLISECOND,0);
       
       return this;
   }
   
   /**
    * Make the date go back of the specified amount of days
    * The internal date is changed after this call.
    *
    * @return a reference to this DateUtil, for concatenation.
    */
   public DateUtil removeDays(int days) {
       
       Date d = cal.getTime();
       long time = d.getTime();
       time -= days * 24 * 3600 * 1000;
       d.setTime(time);
       cal.setTime(d);
       
       return this;
   }
   
   /**
    * Make the date go forward of the specified amount of minutes
    * The internal date is changed after this call.
    *
    * @return a reference to this DateUtil, for concatenation.
    */
   public DateUtil addMinutes(int minutes) {
       Date d = cal.getTime();
       long time = d.getTime();
       time += minutes * 60 * 1000;
       d.setTime(time);
       cal.setTime(d);
       
       return this;
   }
   
   /**
    * Convert the date to GMT. The internal date is changed
    *
    * @return a reference to this DateUtil, for concatenation.
    */
   public DateUtil toGMT() {
       return toTZ("GMT");
   }
   
   /**
    * Convert the date to the given timezone. The internal date is changed.
    *
    * @param tz The name of the timezone to set
    *
    * @return a reference to this DateUtil, for concatenation.
    */
   public DateUtil toTZ(String tz) {
       cal.setTimeZone(TimeZone.getTimeZone(tz));
       
       return this;
   }
   
   /**
    * Get the days passed from the specified date up to the date provided 
    * in the constructor
    *
    * @param date The starting date
    *
    * @return number of days within date used in constructor and the provided
    * date
    */
   public int getDaysSince(Date date) {
       long millisecs = date.getTime();
       Date d = cal.getTime();
       long time = d.getTime();
       long daysMillisecs = time - millisecs;
       int days = (int)((((daysMillisecs / 1000)/60)/60)/24);
       return days;
   }
   
   /**
    * Utility method wrapping Calendar.after method
    * Compares the date field parameter with the date provided with the constructor
    * answering the question: date from constructor is after the given param date ?
    *
    * @param date The date to be used for comparison
    *
    * @return true if date from constructor is after given param date
    */
   public boolean isAfter(Date date) {
       Calendar cal2 = Calendar.getInstance();
       cal2.setTime(date);
       return cal.after(cal2);
   }

}


 </source>
   
  
 
  



Get the hours difference

   <source lang="java">
  

/*

* Copyright Javelin Software, All rights reserved.
*/

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

* The DateUtil is used as a Utility Class for Dates.
* 
* @author Robin Sharp
*/

public class DateUtil {

   public final static long SECOND_MILLIS = 1000;
   public final static long MINUTE_MILLIS = SECOND_MILLIS*60;
   public final static long HOUR_MILLIS = MINUTE_MILLIS*60;
   public final static long DAY_MILLIS = HOUR_MILLIS*24;
   public final static long YEAR_MILLIS = DAY_MILLIS*365;
   public static DateFormat OUT_DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy");
   public static DateFormat OUT_TIME_FORMAT = new SimpleDateFormat("H:mm:ss");
   public static DateFormat OUT_DATETIME_FORMAT = new SimpleDateFormat("d/M/yyyy H:mm:ss");
   public static DateFormat OUT_TIMESTAMP_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss.SSS");
   
   public static DateFormat IN_DATE_FORMAT = new SimpleDateFormat("d/M/yy");
   public static DateFormat IN_TIME_FORMAT = new SimpleDateFormat("H:mm:ss");
   public static DateFormat IN_DATETIME_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss");
   public static DateFormat IN_TIMESTAMP_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss.SSS");
   
   public static DateFormat DATE_TIME_FORMAT= new SimpleDateFormat( "yyyyMMddkkmmss" );  
   public static Calendar calendar = new GregorianCalendar();
   static
   {
       IN_DATE_FORMAT.setLenient(false);
       IN_TIME_FORMAT.setLenient(false);
       IN_DATETIME_FORMAT.setLenient(false);
   }
   /**
    * Create a new DateTime. To the last second. This will not create any 
    * extra-millis-seconds, which may cause bugs when writing to stores such as
    * databases that round milli-seconds up and down. 
    */
   public static java.util.Date newDateTime()
   {
       return new java.util.Date( (System.currentTimeMillis()/SECOND_MILLIS)*SECOND_MILLIS);
   }
   /**
    * Create a new Date. To the last day.
    */
   public static java.sql.Date newDate()
   {
       return new java.sql.Date( (System.currentTimeMillis()/DAY_MILLIS)*DAY_MILLIS);
   }
   
   /**
    * Create a new Time, with no date component. 
    */
   public static java.sql.Time newTime()
   {
       return new java.sql.Time( System.currentTimeMillis()%DAY_MILLIS);
   }
   
   /**
    * Create a new Timestamp. 
    */
   public static java.sql.Timestamp newTimestamp()
   {
       return new java.sql.Timestamp( System.currentTimeMillis() );
   }
   
   /**
    * Get the seconds difference
    */
   public static int secondsDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/SECOND_MILLIS) - (earlierDate.getTime()/SECOND_MILLIS));
   }
   /**
    * Get the minutes difference
    */
   public static int minutesDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/MINUTE_MILLIS) - (earlierDate.getTime()/MINUTE_MILLIS));
   }
   
   /**
    * Get the hours difference
    */
   public static int hoursDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/HOUR_MILLIS) - (earlierDate.getTime()/HOUR_MILLIS));
   }
   
   /**
    * Get the days difference
    */
   public static int daysDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/DAY_MILLIS) - (earlierDate.getTime()/DAY_MILLIS));
   }
   
  /**
   * Roll the java.util.Time forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.sql.Time rollTime( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.sql.Time(gc.getTime().getTime());
   }
   
  /**
   * Roll the java.util.Date forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.util.Date rollDateTime( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.util.Date(gc.getTime().getTime());
   }
   
  /**
   * Roll the java.sql.Date forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.sql.Date rollDate( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.sql.Date(gc.getTime().getTime());
   }
   
  /**
   * Roll the years forward or backward.
   * @param startDate - The start date
   * @param years - Negative to rollbackwards.
   */
   public static java.sql.Date rollYears( java.util.Date startDate, int years )
   {
       return rollDate( startDate, Calendar.YEAR, years );
   }
  /**
   * Roll the days forward or backward.
   * @param startDate - The start date
   * @param months - Negative to rollbackwards.
   */
   public static java.sql.Date rollMonths( java.util.Date startDate, int months )
   {
       return rollDate( startDate, Calendar.MONTH, months );
   }
  /**
   * Roll the days forward or backward.
   * @param startDate - The start date
   * @param days - Negative to rollbackwards.
   */
   public static java.sql.Date rollDays( java.util.Date startDate, int days )
   {
       return rollDate( startDate, Calendar.DATE, days );
   }
   
    /**
     * Checks the day, month and year are equal.
     */
    public static boolean dateEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;
       
       return d1.getDate() == d2.getDate() &&
              d1.getMonth() == d2.getMonth() &&
              d1.getYear() == d2.getYear();
    }
    
    /**
     * Checks the hour, minute and second are equal.
     */
    public static boolean timeEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;
       
       return d1.getHours() == d2.getHours() &&
              d1.getMinutes() == d2.getMinutes() &&
              d1.getSeconds() == d2.getSeconds();
    }
   /**
     * Checks the second, hour, month, day, month and year are equal.
     */
    public static boolean dateTimeEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;               
       
       return d1.getDate() == d2.getDate() &&
              d1.getMonth() == d2.getMonth() &&
              d1.getYear() == d2.getYear() &&
              d1.getHours() == d2.getHours() &&
              d1.getMinutes() == d2.getMinutes() &&
              d1.getSeconds() == d2.getSeconds();
    }
    
    /**
    * Convert an Object of type Classs to an Object.
    */
   public static Object toObject( Class clazz, Object value ) throws ParseException
   {
       if( value == null ) return null;
       if( clazz == null ) return value;
       
       if( java.sql.Date.class.isAssignableFrom( clazz ) ) return toDate( value );
       if( java.sql.Time.class.isAssignableFrom( clazz ) ) return toTime( value );
       if( java.sql.Timestamp.class.isAssignableFrom( clazz ) ) return toTimestamp( value );
       if( java.util.Date.class.isAssignableFrom( clazz ) ) return toDateTime( value );
       
       return value;
   }
   
   /**
    * Convert an Object to a DateTime, without an Exception
    */
   public static java.util.Date getDateTime( Object value )
   {
       try
       {
           return toDateTime( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   
   /**
    * Convert an Object to a DateTime.
    */
   public static java.util.Date toDateTime( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.util.Date ) return (java.util.Date)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return IN_DATETIME_FORMAT.parse( (String)value );
       }
               
       return IN_DATETIME_FORMAT.parse( value.toString() );
   }
   
   /**
    * Convert an Object to a Date, without an Exception
    */
   public static java.sql.Date getDate( Object value )
   {
       try
       {
           return toDate( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   /**
    * Convert an Object to a Date.
    */
   public static java.sql.Date toDate( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Date ) return (java.sql.Date)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Date( IN_DATE_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Date( IN_DATE_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Convert an Object to a Time, without an Exception
    */
   public static java.sql.Time getTime( Object value )
   {
       try
       {
           return toTime( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   
   /**
    * Convert an Object to a Time.
    */
   public static java.sql.Time toTime( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Time ) return (java.sql.Time)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Time( IN_TIME_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Time( IN_TIME_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Convert an Object to a Timestamp, without an Exception
    */
   public static java.sql.Timestamp getTimestamp( Object value )
   {
       try
       {
           return toTimestamp( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   /**
    * Convert an Object to a Timestamp.
    */
   public static java.sql.Timestamp toTimestamp( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Timestamp ) return (java.sql.Timestamp)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Timestamp( IN_TIMESTAMP_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Timestamp( IN_TIMESTAMP_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Tells you if the date part of a datetime is in a certain time range.
    */
   public static boolean isTimeInRange( java.sql.Time start, java.sql.Time end, java.util.Date d )
   {
       d=new java.sql.Time(d.getHours(),d.getMinutes(),d.getSeconds());
       
       if (start==null || end==null)
       {
           return false;
       }
       
       if (start.before(end)&&(!(d.after(start)&&d.before(end))))
       {
           return false;
       }
       
       if (end.before(start)&&(!(d.after(end)||d.before(start))))
       {
           return false;
       }   
       return true;
   }
   public static  int getYear( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.YEAR );
   }
   public static int getMonth( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MONTH );
   }
   public static int getDate( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.DATE );
   }
   public static int getHour( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.HOUR );
   }
   public static int getMinute( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MINUTE );
   }
   public static int getSeconds( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.SECOND );
   }
   public static int getMillisecond( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MILLISECOND );
   }
   
   /**
    * Convert an Object to a String using Dates
    */
   public static String toString( Object date )
   {
       if( date == null ) return null;
       
       if( java.sql.Timestamp.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_TIMESTAMP_FORMAT.format( date );
       }
       if( java.sql.Time.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_TIME_FORMAT.format( date );
       }
       if( java.sql.Date.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_DATE_FORMAT.format( date );
       }
       if( java.util.Date.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_DATETIME_FORMAT.format( date );
       }
       
       throw new IllegalArgumentException( "Unsupported type " + date.getClass() );
   }

}


 </source>
   
  
 
  



Get the minutes difference

   <source lang="java">
  

/*

* Copyright Javelin Software, All rights reserved.
*/

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

* The DateUtil is used as a Utility Class for Dates.
* 
* @author Robin Sharp
*/

public class DateUtil {

   public final static long SECOND_MILLIS = 1000;
   public final static long MINUTE_MILLIS = SECOND_MILLIS*60;
   public final static long HOUR_MILLIS = MINUTE_MILLIS*60;
   public final static long DAY_MILLIS = HOUR_MILLIS*24;
   public final static long YEAR_MILLIS = DAY_MILLIS*365;
   public static DateFormat OUT_DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy");
   public static DateFormat OUT_TIME_FORMAT = new SimpleDateFormat("H:mm:ss");
   public static DateFormat OUT_DATETIME_FORMAT = new SimpleDateFormat("d/M/yyyy H:mm:ss");
   public static DateFormat OUT_TIMESTAMP_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss.SSS");
   
   public static DateFormat IN_DATE_FORMAT = new SimpleDateFormat("d/M/yy");
   public static DateFormat IN_TIME_FORMAT = new SimpleDateFormat("H:mm:ss");
   public static DateFormat IN_DATETIME_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss");
   public static DateFormat IN_TIMESTAMP_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss.SSS");
   
   public static DateFormat DATE_TIME_FORMAT= new SimpleDateFormat( "yyyyMMddkkmmss" );  
   public static Calendar calendar = new GregorianCalendar();
   static
   {
       IN_DATE_FORMAT.setLenient(false);
       IN_TIME_FORMAT.setLenient(false);
       IN_DATETIME_FORMAT.setLenient(false);
   }
   /**
    * Create a new DateTime. To the last second. This will not create any 
    * extra-millis-seconds, which may cause bugs when writing to stores such as
    * databases that round milli-seconds up and down. 
    */
   public static java.util.Date newDateTime()
   {
       return new java.util.Date( (System.currentTimeMillis()/SECOND_MILLIS)*SECOND_MILLIS);
   }
   /**
    * Create a new Date. To the last day.
    */
   public static java.sql.Date newDate()
   {
       return new java.sql.Date( (System.currentTimeMillis()/DAY_MILLIS)*DAY_MILLIS);
   }
   
   /**
    * Create a new Time, with no date component. 
    */
   public static java.sql.Time newTime()
   {
       return new java.sql.Time( System.currentTimeMillis()%DAY_MILLIS);
   }
   
   /**
    * Create a new Timestamp. 
    */
   public static java.sql.Timestamp newTimestamp()
   {
       return new java.sql.Timestamp( System.currentTimeMillis() );
   }
   
   /**
    * Get the seconds difference
    */
   public static int secondsDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/SECOND_MILLIS) - (earlierDate.getTime()/SECOND_MILLIS));
   }
   /**
    * Get the minutes difference
    */
   public static int minutesDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/MINUTE_MILLIS) - (earlierDate.getTime()/MINUTE_MILLIS));
   }
   
   /**
    * Get the hours difference
    */
   public static int hoursDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/HOUR_MILLIS) - (earlierDate.getTime()/HOUR_MILLIS));
   }
   
   /**
    * Get the days difference
    */
   public static int daysDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/DAY_MILLIS) - (earlierDate.getTime()/DAY_MILLIS));
   }
   
  /**
   * Roll the java.util.Time forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.sql.Time rollTime( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.sql.Time(gc.getTime().getTime());
   }
   
  /**
   * Roll the java.util.Date forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.util.Date rollDateTime( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.util.Date(gc.getTime().getTime());
   }
   
  /**
   * Roll the java.sql.Date forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.sql.Date rollDate( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.sql.Date(gc.getTime().getTime());
   }
   
  /**
   * Roll the years forward or backward.
   * @param startDate - The start date
   * @param years - Negative to rollbackwards.
   */
   public static java.sql.Date rollYears( java.util.Date startDate, int years )
   {
       return rollDate( startDate, Calendar.YEAR, years );
   }
  /**
   * Roll the days forward or backward.
   * @param startDate - The start date
   * @param months - Negative to rollbackwards.
   */
   public static java.sql.Date rollMonths( java.util.Date startDate, int months )
   {
       return rollDate( startDate, Calendar.MONTH, months );
   }
  /**
   * Roll the days forward or backward.
   * @param startDate - The start date
   * @param days - Negative to rollbackwards.
   */
   public static java.sql.Date rollDays( java.util.Date startDate, int days )
   {
       return rollDate( startDate, Calendar.DATE, days );
   }
   
    /**
     * Checks the day, month and year are equal.
     */
    public static boolean dateEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;
       
       return d1.getDate() == d2.getDate() &&
              d1.getMonth() == d2.getMonth() &&
              d1.getYear() == d2.getYear();
    }
    
    /**
     * Checks the hour, minute and second are equal.
     */
    public static boolean timeEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;
       
       return d1.getHours() == d2.getHours() &&
              d1.getMinutes() == d2.getMinutes() &&
              d1.getSeconds() == d2.getSeconds();
    }
   /**
     * Checks the second, hour, month, day, month and year are equal.
     */
    public static boolean dateTimeEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;               
       
       return d1.getDate() == d2.getDate() &&
              d1.getMonth() == d2.getMonth() &&
              d1.getYear() == d2.getYear() &&
              d1.getHours() == d2.getHours() &&
              d1.getMinutes() == d2.getMinutes() &&
              d1.getSeconds() == d2.getSeconds();
    }
    
    /**
    * Convert an Object of type Classs to an Object.
    */
   public static Object toObject( Class clazz, Object value ) throws ParseException
   {
       if( value == null ) return null;
       if( clazz == null ) return value;
       
       if( java.sql.Date.class.isAssignableFrom( clazz ) ) return toDate( value );
       if( java.sql.Time.class.isAssignableFrom( clazz ) ) return toTime( value );
       if( java.sql.Timestamp.class.isAssignableFrom( clazz ) ) return toTimestamp( value );
       if( java.util.Date.class.isAssignableFrom( clazz ) ) return toDateTime( value );
       
       return value;
   }
   
   /**
    * Convert an Object to a DateTime, without an Exception
    */
   public static java.util.Date getDateTime( Object value )
   {
       try
       {
           return toDateTime( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   
   /**
    * Convert an Object to a DateTime.
    */
   public static java.util.Date toDateTime( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.util.Date ) return (java.util.Date)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return IN_DATETIME_FORMAT.parse( (String)value );
       }
               
       return IN_DATETIME_FORMAT.parse( value.toString() );
   }
   
   /**
    * Convert an Object to a Date, without an Exception
    */
   public static java.sql.Date getDate( Object value )
   {
       try
       {
           return toDate( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   /**
    * Convert an Object to a Date.
    */
   public static java.sql.Date toDate( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Date ) return (java.sql.Date)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Date( IN_DATE_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Date( IN_DATE_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Convert an Object to a Time, without an Exception
    */
   public static java.sql.Time getTime( Object value )
   {
       try
       {
           return toTime( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   
   /**
    * Convert an Object to a Time.
    */
   public static java.sql.Time toTime( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Time ) return (java.sql.Time)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Time( IN_TIME_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Time( IN_TIME_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Convert an Object to a Timestamp, without an Exception
    */
   public static java.sql.Timestamp getTimestamp( Object value )
   {
       try
       {
           return toTimestamp( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   /**
    * Convert an Object to a Timestamp.
    */
   public static java.sql.Timestamp toTimestamp( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Timestamp ) return (java.sql.Timestamp)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Timestamp( IN_TIMESTAMP_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Timestamp( IN_TIMESTAMP_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Tells you if the date part of a datetime is in a certain time range.
    */
   public static boolean isTimeInRange( java.sql.Time start, java.sql.Time end, java.util.Date d )
   {
       d=new java.sql.Time(d.getHours(),d.getMinutes(),d.getSeconds());
       
       if (start==null || end==null)
       {
           return false;
       }
       
       if (start.before(end)&&(!(d.after(start)&&d.before(end))))
       {
           return false;
       }
       
       if (end.before(start)&&(!(d.after(end)||d.before(start))))
       {
           return false;
       }   
       return true;
   }
   public static  int getYear( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.YEAR );
   }
   public static int getMonth( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MONTH );
   }
   public static int getDate( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.DATE );
   }
   public static int getHour( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.HOUR );
   }
   public static int getMinute( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MINUTE );
   }
   public static int getSeconds( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.SECOND );
   }
   public static int getMillisecond( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MILLISECOND );
   }
   
   /**
    * Convert an Object to a String using Dates
    */
   public static String toString( Object date )
   {
       if( date == null ) return null;
       
       if( java.sql.Timestamp.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_TIMESTAMP_FORMAT.format( date );
       }
       if( java.sql.Time.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_TIME_FORMAT.format( date );
       }
       if( java.sql.Date.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_DATE_FORMAT.format( date );
       }
       if( java.util.Date.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_DATETIME_FORMAT.format( date );
       }
       
       throw new IllegalArgumentException( "Unsupported type " + date.getClass() );
   }

}


 </source>
   
  
 
  



Get the seconds difference

   <source lang="java">
  

/*

* Copyright Javelin Software, All rights reserved.
*/

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

* The DateUtil is used as a Utility Class for Dates.
* 
* @author Robin Sharp
*/

public class DateUtil {

   public final static long SECOND_MILLIS = 1000;
   public final static long MINUTE_MILLIS = SECOND_MILLIS*60;
   public final static long HOUR_MILLIS = MINUTE_MILLIS*60;
   public final static long DAY_MILLIS = HOUR_MILLIS*24;
   public final static long YEAR_MILLIS = DAY_MILLIS*365;
   public static DateFormat OUT_DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy");
   public static DateFormat OUT_TIME_FORMAT = new SimpleDateFormat("H:mm:ss");
   public static DateFormat OUT_DATETIME_FORMAT = new SimpleDateFormat("d/M/yyyy H:mm:ss");
   public static DateFormat OUT_TIMESTAMP_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss.SSS");
   
   public static DateFormat IN_DATE_FORMAT = new SimpleDateFormat("d/M/yy");
   public static DateFormat IN_TIME_FORMAT = new SimpleDateFormat("H:mm:ss");
   public static DateFormat IN_DATETIME_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss");
   public static DateFormat IN_TIMESTAMP_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss.SSS");
   
   public static DateFormat DATE_TIME_FORMAT= new SimpleDateFormat( "yyyyMMddkkmmss" );  
   public static Calendar calendar = new GregorianCalendar();
   static
   {
       IN_DATE_FORMAT.setLenient(false);
       IN_TIME_FORMAT.setLenient(false);
       IN_DATETIME_FORMAT.setLenient(false);
   }
   /**
    * Create a new DateTime. To the last second. This will not create any 
    * extra-millis-seconds, which may cause bugs when writing to stores such as
    * databases that round milli-seconds up and down. 
    */
   public static java.util.Date newDateTime()
   {
       return new java.util.Date( (System.currentTimeMillis()/SECOND_MILLIS)*SECOND_MILLIS);
   }
   /**
    * Create a new Date. To the last day.
    */
   public static java.sql.Date newDate()
   {
       return new java.sql.Date( (System.currentTimeMillis()/DAY_MILLIS)*DAY_MILLIS);
   }
   
   /**
    * Create a new Time, with no date component. 
    */
   public static java.sql.Time newTime()
   {
       return new java.sql.Time( System.currentTimeMillis()%DAY_MILLIS);
   }
   
   /**
    * Create a new Timestamp. 
    */
   public static java.sql.Timestamp newTimestamp()
   {
       return new java.sql.Timestamp( System.currentTimeMillis() );
   }
   
   /**
    * Get the seconds difference
    */
   public static int secondsDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/SECOND_MILLIS) - (earlierDate.getTime()/SECOND_MILLIS));
   }
   /**
    * Get the minutes difference
    */
   public static int minutesDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/MINUTE_MILLIS) - (earlierDate.getTime()/MINUTE_MILLIS));
   }
   
   /**
    * Get the hours difference
    */
   public static int hoursDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/HOUR_MILLIS) - (earlierDate.getTime()/HOUR_MILLIS));
   }
   
   /**
    * Get the days difference
    */
   public static int daysDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/DAY_MILLIS) - (earlierDate.getTime()/DAY_MILLIS));
   }
   
  /**
   * Roll the java.util.Time forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.sql.Time rollTime( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.sql.Time(gc.getTime().getTime());
   }
   
  /**
   * Roll the java.util.Date forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.util.Date rollDateTime( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.util.Date(gc.getTime().getTime());
   }
   
  /**
   * Roll the java.sql.Date forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.sql.Date rollDate( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.sql.Date(gc.getTime().getTime());
   }
   
  /**
   * Roll the years forward or backward.
   * @param startDate - The start date
   * @param years - Negative to rollbackwards.
   */
   public static java.sql.Date rollYears( java.util.Date startDate, int years )
   {
       return rollDate( startDate, Calendar.YEAR, years );
   }
  /**
   * Roll the days forward or backward.
   * @param startDate - The start date
   * @param months - Negative to rollbackwards.
   */
   public static java.sql.Date rollMonths( java.util.Date startDate, int months )
   {
       return rollDate( startDate, Calendar.MONTH, months );
   }
  /**
   * Roll the days forward or backward.
   * @param startDate - The start date
   * @param days - Negative to rollbackwards.
   */
   public static java.sql.Date rollDays( java.util.Date startDate, int days )
   {
       return rollDate( startDate, Calendar.DATE, days );
   }
   
    /**
     * Checks the day, month and year are equal.
     */
    public static boolean dateEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;
       
       return d1.getDate() == d2.getDate() &&
              d1.getMonth() == d2.getMonth() &&
              d1.getYear() == d2.getYear();
    }
    
    /**
     * Checks the hour, minute and second are equal.
     */
    public static boolean timeEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;
       
       return d1.getHours() == d2.getHours() &&
              d1.getMinutes() == d2.getMinutes() &&
              d1.getSeconds() == d2.getSeconds();
    }
   /**
     * Checks the second, hour, month, day, month and year are equal.
     */
    public static boolean dateTimeEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;               
       
       return d1.getDate() == d2.getDate() &&
              d1.getMonth() == d2.getMonth() &&
              d1.getYear() == d2.getYear() &&
              d1.getHours() == d2.getHours() &&
              d1.getMinutes() == d2.getMinutes() &&
              d1.getSeconds() == d2.getSeconds();
    }
    
    /**
    * Convert an Object of type Classs to an Object.
    */
   public static Object toObject( Class clazz, Object value ) throws ParseException
   {
       if( value == null ) return null;
       if( clazz == null ) return value;
       
       if( java.sql.Date.class.isAssignableFrom( clazz ) ) return toDate( value );
       if( java.sql.Time.class.isAssignableFrom( clazz ) ) return toTime( value );
       if( java.sql.Timestamp.class.isAssignableFrom( clazz ) ) return toTimestamp( value );
       if( java.util.Date.class.isAssignableFrom( clazz ) ) return toDateTime( value );
       
       return value;
   }
   
   /**
    * Convert an Object to a DateTime, without an Exception
    */
   public static java.util.Date getDateTime( Object value )
   {
       try
       {
           return toDateTime( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   
   /**
    * Convert an Object to a DateTime.
    */
   public static java.util.Date toDateTime( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.util.Date ) return (java.util.Date)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return IN_DATETIME_FORMAT.parse( (String)value );
       }
               
       return IN_DATETIME_FORMAT.parse( value.toString() );
   }
   
   /**
    * Convert an Object to a Date, without an Exception
    */
   public static java.sql.Date getDate( Object value )
   {
       try
       {
           return toDate( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   /**
    * Convert an Object to a Date.
    */
   public static java.sql.Date toDate( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Date ) return (java.sql.Date)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Date( IN_DATE_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Date( IN_DATE_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Convert an Object to a Time, without an Exception
    */
   public static java.sql.Time getTime( Object value )
   {
       try
       {
           return toTime( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   
   /**
    * Convert an Object to a Time.
    */
   public static java.sql.Time toTime( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Time ) return (java.sql.Time)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Time( IN_TIME_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Time( IN_TIME_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Convert an Object to a Timestamp, without an Exception
    */
   public static java.sql.Timestamp getTimestamp( Object value )
   {
       try
       {
           return toTimestamp( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   /**
    * Convert an Object to a Timestamp.
    */
   public static java.sql.Timestamp toTimestamp( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Timestamp ) return (java.sql.Timestamp)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Timestamp( IN_TIMESTAMP_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Timestamp( IN_TIMESTAMP_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Tells you if the date part of a datetime is in a certain time range.
    */
   public static boolean isTimeInRange( java.sql.Time start, java.sql.Time end, java.util.Date d )
   {
       d=new java.sql.Time(d.getHours(),d.getMinutes(),d.getSeconds());
       
       if (start==null || end==null)
       {
           return false;
       }
       
       if (start.before(end)&&(!(d.after(start)&&d.before(end))))
       {
           return false;
       }
       
       if (end.before(start)&&(!(d.after(end)||d.before(start))))
       {
           return false;
       }   
       return true;
   }
   public static  int getYear( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.YEAR );
   }
   public static int getMonth( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MONTH );
   }
   public static int getDate( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.DATE );
   }
   public static int getHour( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.HOUR );
   }
   public static int getMinute( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MINUTE );
   }
   public static int getSeconds( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.SECOND );
   }
   public static int getMillisecond( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MILLISECOND );
   }
   
   /**
    * Convert an Object to a String using Dates
    */
   public static String toString( Object date )
   {
       if( date == null ) return null;
       
       if( java.sql.Timestamp.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_TIMESTAMP_FORMAT.format( date );
       }
       if( java.sql.Time.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_TIME_FORMAT.format( date );
       }
       if( java.sql.Date.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_DATE_FORMAT.format( date );
       }
       if( java.util.Date.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_DATETIME_FORMAT.format( date );
       }
       
       throw new IllegalArgumentException( "Unsupported type " + date.getClass() );
   }

}


 </source>
   
  
 
  



Make the date go back of the specified amount of days

   <source lang="java">
 

/*

* Funambol is a mobile platform developed by Funambol, Inc. 
* Copyright (C) 2003 - 2007 Funambol, Inc.
* 
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission 
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE 
* WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
* 
* 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 General Public License for more
* details.
* 
* You should have received a copy of the GNU Affero General Public License 
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
* 
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite 
* 305, Redwood City, CA 94063, USA, or at email address info@funambol.ru.
* 
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
* 
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably 
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/

import java.util.Calendar; import java.util.Date; import java.util.TimeZone;

/**

* Utility class for date manipulation.
* This class gives a simple interface for common Date, Calendar and Timezone
* operations.
* It is possible to apply subsequent transformations to an initial date, and
* retrieve the changed Date object at any point.
*
*/

public class DateUtil {

   //-------------------------------------------------------------- Attributes
   private Calendar cal;
   
   //------------------------------------------------------------ Constructors
   
   /** Inizialize a new instance with the current date */
   public DateUtil() {
       this(new Date());
   }
   
   /** Inizialize a new instance with the given date */
   public DateUtil(Date d) {
       cal = Calendar.getInstance();
       cal.setTime(d);
   }
   
   //---------------------------------------------------------- Public methods
   
   /** Set a new time */
   public void setTime(Date d) {
       cal.setTime(d);
   }
   
   /** Get the current time */
   public Date getTime() {
       return cal.getTime();
   }
   
   /** Get the current TimeZone */
   public String getTZ() {
       return cal.getTimeZone().getID();
   }
   
   /**
    * Convert the time to the midnight of the currently set date.
    * The internal date is changed after this call.
    *
    * @return a reference to this DateUtil, for concatenation.
    */
   public DateUtil toMidnight() {
       
       cal.set(Calendar.HOUR_OF_DAY, 0);
       cal.set(Calendar.MINUTE, 0);
       cal.set(Calendar.SECOND, 0);
       cal.set(Calendar.MILLISECOND,0);
       
       return this;
   }
   
   /**
    * Make the date go back of the specified amount of days
    * The internal date is changed after this call.
    *
    * @return a reference to this DateUtil, for concatenation.
    */
   public DateUtil removeDays(int days) {
       
       Date d = cal.getTime();
       long time = d.getTime();
       time -= days * 24 * 3600 * 1000;
       d.setTime(time);
       cal.setTime(d);
       
       return this;
   }
   
   /**
    * Make the date go forward of the specified amount of minutes
    * The internal date is changed after this call.
    *
    * @return a reference to this DateUtil, for concatenation.
    */
   public DateUtil addMinutes(int minutes) {
       Date d = cal.getTime();
       long time = d.getTime();
       time += minutes * 60 * 1000;
       d.setTime(time);
       cal.setTime(d);
       
       return this;
   }
   
   /**
    * Convert the date to GMT. The internal date is changed
    *
    * @return a reference to this DateUtil, for concatenation.
    */
   public DateUtil toGMT() {
       return toTZ("GMT");
   }
   
   /**
    * Convert the date to the given timezone. The internal date is changed.
    *
    * @param tz The name of the timezone to set
    *
    * @return a reference to this DateUtil, for concatenation.
    */
   public DateUtil toTZ(String tz) {
       cal.setTimeZone(TimeZone.getTimeZone(tz));
       
       return this;
   }
   
   /**
    * Get the days passed from the specified date up to the date provided 
    * in the constructor
    *
    * @param date The starting date
    *
    * @return number of days within date used in constructor and the provided
    * date
    */
   public int getDaysSince(Date date) {
       long millisecs = date.getTime();
       Date d = cal.getTime();
       long time = d.getTime();
       long daysMillisecs = time - millisecs;
       int days = (int)((((daysMillisecs / 1000)/60)/60)/24);
       return days;
   }
   
   /**
    * Utility method wrapping Calendar.after method
    * Compares the date field parameter with the date provided with the constructor
    * answering the question: date from constructor is after the given param date ?
    *
    * @param date The date to be used for comparison
    *
    * @return true if date from constructor is after given param date
    */
   public boolean isAfter(Date date) {
       Calendar cal2 = Calendar.getInstance();
       cal2.setTime(date);
       return cal.after(cal2);
   }

}


 </source>
   
  
 
  



Make the date go forward of the specified amount of minutes

   <source lang="java">
 

/*

* Funambol is a mobile platform developed by Funambol, Inc. 
* Copyright (C) 2003 - 2007 Funambol, Inc.
* 
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission 
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE 
* WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
* 
* 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 General Public License for more
* details.
* 
* You should have received a copy of the GNU Affero General Public License 
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
* 
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite 
* 305, Redwood City, CA 94063, USA, or at email address info@funambol.ru.
* 
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
* 
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably 
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/

import java.util.Calendar; import java.util.Date; import java.util.TimeZone;

/**

* Utility class for date manipulation.
* This class gives a simple interface for common Date, Calendar and Timezone
* operations.
* It is possible to apply subsequent transformations to an initial date, and
* retrieve the changed Date object at any point.
*
*/

public class DateUtil {

   //-------------------------------------------------------------- Attributes
   private Calendar cal;
   
   //------------------------------------------------------------ Constructors
   
   /** Inizialize a new instance with the current date */
   public DateUtil() {
       this(new Date());
   }
   
   /** Inizialize a new instance with the given date */
   public DateUtil(Date d) {
       cal = Calendar.getInstance();
       cal.setTime(d);
   }
   
   //---------------------------------------------------------- Public methods
   
   /** Set a new time */
   public void setTime(Date d) {
       cal.setTime(d);
   }
   
   /** Get the current time */
   public Date getTime() {
       return cal.getTime();
   }
   
   /** Get the current TimeZone */
   public String getTZ() {
       return cal.getTimeZone().getID();
   }
   
   /**
    * Convert the time to the midnight of the currently set date.
    * The internal date is changed after this call.
    *
    * @return a reference to this DateUtil, for concatenation.
    */
   public DateUtil toMidnight() {
       
       cal.set(Calendar.HOUR_OF_DAY, 0);
       cal.set(Calendar.MINUTE, 0);
       cal.set(Calendar.SECOND, 0);
       cal.set(Calendar.MILLISECOND,0);
       
       return this;
   }
   
   /**
    * Make the date go back of the specified amount of days
    * The internal date is changed after this call.
    *
    * @return a reference to this DateUtil, for concatenation.
    */
   public DateUtil removeDays(int days) {
       
       Date d = cal.getTime();
       long time = d.getTime();
       time -= days * 24 * 3600 * 1000;
       d.setTime(time);
       cal.setTime(d);
       
       return this;
   }
   
   /**
    * Make the date go forward of the specified amount of minutes
    * The internal date is changed after this call.
    *
    * @return a reference to this DateUtil, for concatenation.
    */
   public DateUtil addMinutes(int minutes) {
       Date d = cal.getTime();
       long time = d.getTime();
       time += minutes * 60 * 1000;
       d.setTime(time);
       cal.setTime(d);
       
       return this;
   }
   
   /**
    * Convert the date to GMT. The internal date is changed
    *
    * @return a reference to this DateUtil, for concatenation.
    */
   public DateUtil toGMT() {
       return toTZ("GMT");
   }
   
   /**
    * Convert the date to the given timezone. The internal date is changed.
    *
    * @param tz The name of the timezone to set
    *
    * @return a reference to this DateUtil, for concatenation.
    */
   public DateUtil toTZ(String tz) {
       cal.setTimeZone(TimeZone.getTimeZone(tz));
       
       return this;
   }
   
   /**
    * Get the days passed from the specified date up to the date provided 
    * in the constructor
    *
    * @param date The starting date
    *
    * @return number of days within date used in constructor and the provided
    * date
    */
   public int getDaysSince(Date date) {
       long millisecs = date.getTime();
       Date d = cal.getTime();
       long time = d.getTime();
       long daysMillisecs = time - millisecs;
       int days = (int)((((daysMillisecs / 1000)/60)/60)/24);
       return days;
   }
   
   /**
    * Utility method wrapping Calendar.after method
    * Compares the date field parameter with the date provided with the constructor
    * answering the question: date from constructor is after the given param date ?
    *
    * @param date The date to be used for comparison
    *
    * @return true if date from constructor is after given param date
    */
   public boolean isAfter(Date date) {
       Calendar cal2 = Calendar.getInstance();
       cal2.setTime(date);
       return cal.after(cal2);
   }

}


 </source>
   
  
 
  



Returns a Date set just to Noon, to the closest possible millisecond of the day.

   <source lang="java">
 

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
*  contributor license agreements.  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.  For additional information regarding
* copyright in this work, please see the NOTICE file in the top level
* directory of this distribution.
*/

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

 /**
  * Returns a Date set just to Noon, to the closest possible millisecond
  * of the day. If a null day is passed in, a new Date is created.
  * nnoon (00m 12h 00s)
  */
 public static Date getNoonOfDay(Date day, Calendar cal) {
     if (day == null) day = new Date();
     cal.setTime(day);
     cal.set(Calendar.HOUR_OF_DAY, 12);
     cal.set(Calendar.MINUTE,      cal.getMinimum(Calendar.MINUTE));
     cal.set(Calendar.SECOND,      cal.getMinimum(Calendar.SECOND));
     cal.set(Calendar.MILLISECOND, cal.getMinimum(Calendar.MILLISECOND));
     return cal.getTime();
 }

}


 </source>
   
  
 
  



Returns a Date set to the first possible millisecond of the day, just after midnight.

   <source lang="java">
 

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
*  contributor license agreements.  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.  For additional information regarding
* copyright in this work, please see the NOTICE file in the top level
* directory of this distribution.
*/

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

 /**
  * Returns a Date set to the first possible millisecond of the day, just
  * after midnight. If a null day is passed in, a new Date is created.
  * midnight (00m 00h 00s)
  */
 public static Date getStartOfDay(Date day) {
     return getStartOfDay(day, Calendar.getInstance());
 }
 
 
 /**
  * Returns a Date set to the first possible millisecond of the day, just
  * after midnight. If a null day is passed in, a new Date is created.
  * midnight (00m 00h 00s)
  */
 public static Date getStartOfDay(Date day, Calendar cal) {
     if (day == null) day = new Date();
     cal.setTime(day);
     cal.set(Calendar.HOUR_OF_DAY, cal.getMinimum(Calendar.HOUR_OF_DAY));
     cal.set(Calendar.MINUTE,      cal.getMinimum(Calendar.MINUTE));
     cal.set(Calendar.SECOND,      cal.getMinimum(Calendar.SECOND));
     cal.set(Calendar.MILLISECOND, cal.getMinimum(Calendar.MILLISECOND));
     return cal.getTime();
 }

}


 </source>
   
  
 
  



Returns a Date set to the first possible millisecond of the month, just after midnight.

   <source lang="java">
 

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
*  contributor license agreements.  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.  For additional information regarding
* copyright in this work, please see the NOTICE file in the top level
* directory of this distribution.
*/

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

 /**
  * Returns a Date set to the first possible millisecond of the month, just
  * after midnight. If a null day is passed in, a new Date is created.
  * midnight (00m 00h 00s)
  */
 public static Date getStartOfMonth(Date day) {
     return getStartOfMonth(day, Calendar.getInstance());
 }
 
 
 public static Date getStartOfMonth(Date day, Calendar cal) {
     if (day == null) day = new Date();
     cal.setTime(day);
     
     // set time to start of day
     cal.set(Calendar.HOUR_OF_DAY, cal.getMinimum(Calendar.HOUR_OF_DAY));
     cal.set(Calendar.MINUTE,      cal.getMinimum(Calendar.MINUTE));
     cal.set(Calendar.SECOND,      cal.getMinimum(Calendar.SECOND));
     cal.set(Calendar.MILLISECOND, cal.getMinimum(Calendar.MILLISECOND));
     
     // set time to first day of month
     cal.set(Calendar.DAY_OF_MONTH, 1);
     
     return cal.getTime();
 }

}


 </source>
   
  
 
  



Returns a Date set to the last possible millisecond of the day, just before midnight.

   <source lang="java">
 

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
*  contributor license agreements.  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.  For additional information regarding
* copyright in this work, please see the NOTICE file in the top level
* directory of this distribution.
*/

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

 /**
  * Returns a Date set to the last possible millisecond of the day, just
  * before midnight. If a null day is passed in, a new Date is created.
  * midnight (00m 00h 00s)
  */
 public static Date getEndOfDay(Date day) {
     return getEndOfDay(day,Calendar.getInstance());
 }
 
 
 public static Date getEndOfDay(Date day,Calendar cal) {
     if (day == null) day = new Date();
     cal.setTime(day);
     cal.set(Calendar.HOUR_OF_DAY, cal.getMaximum(Calendar.HOUR_OF_DAY));
     cal.set(Calendar.MINUTE,      cal.getMaximum(Calendar.MINUTE));
     cal.set(Calendar.SECOND,      cal.getMaximum(Calendar.SECOND));
     cal.set(Calendar.MILLISECOND, cal.getMaximum(Calendar.MILLISECOND));
     return cal.getTime();
 }

}


 </source>
   
  
 
  



Returns a Date set to the last possible millisecond of the minute.

   <source lang="java">
 

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
*  contributor license agreements.  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.  For additional information regarding
* copyright in this work, please see the NOTICE file in the top level
* directory of this distribution.
*/

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

 /**
  * Returns a Date set to the last possible millisecond of the minute.
  * If a null day is passed in, a new Date is created.
  */
 public static Date getEndOfMinute(Date day) {
     return getEndOfMinute(day, Calendar.getInstance());
 }
 
 
 public static Date getEndOfMinute(Date day, Calendar cal) {
     if (day == null || cal == null) {
         return day;
     }
     
     cal.setTime(day);
     cal.set(Calendar.SECOND,      cal.getMaximum(Calendar.SECOND));
     cal.set(Calendar.MILLISECOND, cal.getMaximum(Calendar.MILLISECOND));
     return cal.getTime();
 }

}


 </source>
   
  
 
  



Returns a Date set to the last possible millisecond of the month, just before midnight.

   <source lang="java">
 

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
*  contributor license agreements.  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.  For additional information regarding
* copyright in this work, please see the NOTICE file in the top level
* directory of this distribution.
*/

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

 /**
  * Returns a Date set to the last possible millisecond of the month, just
  * before midnight. If a null day is passed in, a new Date is created.
  * midnight (00m 00h 00s)
  */
 public static Date getEndOfMonth(Date day) {
     return getEndOfMonth(day, Calendar.getInstance());
 }
 
 
 public static Date getEndOfMonth(Date day,Calendar cal) {
     if (day == null) day = new Date();
     cal.setTime(day);
     
     // set time to end of day
     cal.set(Calendar.HOUR_OF_DAY, cal.getMaximum(Calendar.HOUR_OF_DAY));
     cal.set(Calendar.MINUTE,      cal.getMaximum(Calendar.MINUTE));
     cal.set(Calendar.SECOND,      cal.getMaximum(Calendar.SECOND));
     cal.set(Calendar.MILLISECOND, cal.getMaximum(Calendar.MILLISECOND));
     
     // set time to first day of month
     cal.set(Calendar.DAY_OF_MONTH, 1);
     
     // add one month
     cal.add(Calendar.MONTH, 1);
     
     // back up one day
     cal.add(Calendar.DAY_OF_MONTH, -1);
     
     return cal.getTime();
 }

}


 </source>
   
  
 
  



Returns a java.sql.Timestamp equal to the current time

   <source lang="java">
 

public class Utils {

 /**
  * Returns a java.sql.Timestamp equal to the current time
  **/
 public static java.sql.Timestamp now() {
     return new java.sql.Timestamp(new java.util.Date().getTime());
 }

}


 </source>
   
  
 
  



Returns the maximum of two dates. A null date is treated as being less than any non-null date

   <source lang="java">
 

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

   /**
*

Checks if two dates are on the same day ignoring time.

    * @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
    */
   public static boolean isSameDay(Date date1, Date date2) {
       if (date1 == null || date2 == null) {
           throw new IllegalArgumentException("The dates 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 calendars represent the same day ignoring time.

    * @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
    */
   public static boolean isSameDay(Calendar cal1, Calendar cal2) {
       if (cal1 == null || cal2 == null) {
           throw new IllegalArgumentException("The dates 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));
   }
   
   /**
*

Checks if a date is today.

    * @param date the date, not altered, not null.
    * @return true if the date is today.
    * @throws IllegalArgumentException if the date is null
    */
   public static boolean isToday(Date date) {
       return isSameDay(date, Calendar.getInstance().getTime());
   }
   
   /**
*

Checks if a calendar date is today.

    * @param cal  the calendar, not altered, not null
    * @return true if cal date is today
    * @throws IllegalArgumentException if the calendar is null
    */
   public static boolean isToday(Calendar cal) {
       return isSameDay(cal, Calendar.getInstance());
   }
   
   /**
*

Checks if the first date is before the second date ignoring time.

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

Checks if the first calendar date is before the second calendar date ignoring time.

    * @param cal1 the first calendar, not altered, not null.
    * @param cal2 the second calendar, not altered, not null.
    * @return true if cal1 date is before cal2 date ignoring time.
    * @throws IllegalArgumentException if either of the calendars are null
    */
   public static boolean isBeforeDay(Calendar cal1, Calendar cal2) {
       if (cal1 == null || cal2 == null) {
           throw new IllegalArgumentException("The dates must not be null");
       }
       if (cal1.get(Calendar.ERA) < cal2.get(Calendar.ERA)) return true;
       if (cal1.get(Calendar.ERA) > cal2.get(Calendar.ERA)) return false;
       if (cal1.get(Calendar.YEAR) < cal2.get(Calendar.YEAR)) return true;
       if (cal1.get(Calendar.YEAR) > cal2.get(Calendar.YEAR)) return false;
       return cal1.get(Calendar.DAY_OF_YEAR) < cal2.get(Calendar.DAY_OF_YEAR);
   }
   
   /**
*

Checks if the first date is after the second date ignoring time.

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

Checks if the first calendar date is after the second calendar date ignoring time.

    * @param cal1 the first calendar, not altered, not null.
    * @param cal2 the second calendar, not altered, not null.
    * @return true if cal1 date is after cal2 date ignoring time.
    * @throws IllegalArgumentException if either of the calendars are null
    */
   public static boolean isAfterDay(Calendar cal1, Calendar cal2) {
       if (cal1 == null || cal2 == null) {
           throw new IllegalArgumentException("The dates must not be null");
       }
       if (cal1.get(Calendar.ERA) < cal2.get(Calendar.ERA)) return false;
       if (cal1.get(Calendar.ERA) > cal2.get(Calendar.ERA)) return true;
       if (cal1.get(Calendar.YEAR) < cal2.get(Calendar.YEAR)) return false;
       if (cal1.get(Calendar.YEAR) > cal2.get(Calendar.YEAR)) return true;
       return cal1.get(Calendar.DAY_OF_YEAR) > cal2.get(Calendar.DAY_OF_YEAR);
   }
   
   /**
*

Checks if a date is after today and within a number of days in the future.

    * @param date the date to check, not altered, not null.
    * @param days the number of days.
    * @return true if the date day is after today and within days in the future .
    * @throws IllegalArgumentException if the date is null
    */
   public static boolean isWithinDaysFuture(Date date, int days) {
       if (date == null) {
           throw new IllegalArgumentException("The date must not be null");
       }
       Calendar cal = Calendar.getInstance();
       cal.setTime(date);
       return isWithinDaysFuture(cal, days);
   }
   
   /**
*

Checks if a calendar date is after today and within a number of days in the future.

    * @param cal the calendar, not altered, not null
    * @param days the number of days.
    * @return true if the calendar date day is after today and within days in the future .
    * @throws IllegalArgumentException if the calendar is null
    */
   public static boolean isWithinDaysFuture(Calendar cal, int days) {
       if (cal == null) {
           throw new IllegalArgumentException("The date must not be null");
       }
       Calendar today = Calendar.getInstance();
       Calendar future = Calendar.getInstance();
       future.add(Calendar.DAY_OF_YEAR, days);
       return (isAfterDay(cal, today) && ! isAfterDay(cal, future));
   }
   
   /** Returns the given date with the time set to the start of the day. */
   public static Date getStart(Date date) {
       return clearTime(date);
   }
   
   /** Returns the given date with the time values cleared. */
   public static Date clearTime(Date date) {
       if (date == null) {
           return null;
       }
       Calendar c = Calendar.getInstance();
       c.setTime(date);
       c.set(Calendar.HOUR_OF_DAY, 0);
       c.set(Calendar.MINUTE, 0);
       c.set(Calendar.SECOND, 0);
       c.set(Calendar.MILLISECOND, 0);
       return c.getTime();
   }    
   /** Determines whether or not a date has any time values (hour, minute, 
    * seconds or millisecondsReturns the given date with the time values cleared. */
   /**
    * Determines whether or not a date has any time values.
    * @param date The date.
    * @return true iff the date is not null and any of the date"s hour, minute,
    * seconds or millisecond values are greater than zero.
    */
   public static boolean hasTime(Date date) {
       if (date == null) {
           return false;
       }
       Calendar c = Calendar.getInstance();
       c.setTime(date);
       if (c.get(Calendar.HOUR_OF_DAY) > 0) {
           return true;
       }
       if (c.get(Calendar.MINUTE) > 0) {
           return true;
       }
       if (c.get(Calendar.SECOND) > 0) {
           return true;
       }
       if (c.get(Calendar.MILLISECOND) > 0) {
           return true;
       }
       return false;
   }
   /** Returns the given date with time set to the end of the day */
   public static Date getEnd(Date date) {
       if (date == null) {
           return null;
       }
       Calendar c = Calendar.getInstance();
       c.setTime(date);
       c.set(Calendar.HOUR_OF_DAY, 23);
       c.set(Calendar.MINUTE, 59);
       c.set(Calendar.SECOND, 59);
       c.set(Calendar.MILLISECOND, 999);
       return c.getTime();
   }
   /** 
    * Returns the maximum of two dates. A null date is treated as being less
    * than any non-null date. 
    */
   public static Date max(Date d1, Date d2) {
       if (d1 == null && d2 == null) return null;
       if (d1 == null) return d2;
       if (d2 == null) return d1;
       return (d1.after(d2)) ? d1 : d2;
   }
   
   /** 
    * Returns the minimum of two dates. A null date is treated as being greater
    * than any non-null date. 
    */
   public static Date min(Date d1, Date d2) {
       if (d1 == null && d2 == null) return null;
       if (d1 == null) return d2;
       if (d2 == null) return d1;
       return (d1.before(d2)) ? d1 : d2;
   }
   /** The maximum date possible. */
   public static Date MAX_DATE = new Date(Long.MAX_VALUE);
   

}


 </source>
   
  
 
  



Returns the number of days within the fragment.

   <source lang="java">
 

import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.TimeZone;

/**

* 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 {

 /**
  * The UTC time zone  (often referred to as GMT).
  */
 public static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("GMT");
 /**
  * Number of milliseconds in a standard second.
  * @since 2.1
  */
 public static final long MILLIS_PER_SECOND = 1000;
 /**
  * Number of milliseconds in a standard minute.
  * @since 2.1
  */
 public static final long MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND;
 /**
  * Number of milliseconds in a standard hour.
  * @since 2.1
  */
 public static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE;
 /**
  * Number of milliseconds in a standard day.
  * @since 2.1
  */
 public static final long MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR;
 /**
  * This is half a month, so this represents whether a date is in the top
  * or bottom half of the month.
  */
 public final static int SEMI_MONTH = 1001;
 private static final int[][] fields = {
         {Calendar.MILLISECOND},
         {Calendar.SECOND},
         {Calendar.MINUTE},
         {Calendar.HOUR_OF_DAY, Calendar.HOUR},
         {Calendar.DATE, Calendar.DAY_OF_MONTH, Calendar.AM_PM 
             /* Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK, Calendar.DAY_OF_WEEK_IN_MONTH */
         },
         {Calendar.MONTH, DateUtils.SEMI_MONTH},
         {Calendar.YEAR},
         {Calendar.ERA}};
 /**
  * A week range, starting on Sunday.
  */
 public final static int RANGE_WEEK_SUNDAY = 1;
 /**
  * A week range, starting on Monday.
  */
 public final static int RANGE_WEEK_MONDAY = 2;
 /**
  * A week range, starting on the day focused.
  */
 public final static int RANGE_WEEK_RELATIVE = 3;
 /**
  * A week range, centered around the day focused.
  */
 public final static int RANGE_WEEK_CENTER = 4;
 /**
  * A month range, the week starting on Sunday.
  */
 public final static int RANGE_MONTH_SUNDAY = 5;
 /**
  * A month range, the week starting on Monday.
  */
 public final static int RANGE_MONTH_MONDAY = 6;
 
 /**
*

Returns the number of days within the * fragment. All datefields greater than the fragment will be ignored.

  * 
*

Asking the days of any date will only return the number of days * of the current month (resulting in a number between 1 and 31). This * method will retrieve the number of days for any fragment. * For example, if you want to calculate the number of days past this year, * your fragment is Calendar.YEAR. The result will be all days of the * past month(s).

  * 
*

Valid fragments are: Calendar.YEAR, Calendar.MONTH, both * Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY, * Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND * A fragment less than or equal to a DAY field will return 0.

  * 
*

*

    *
  • January 28, 2008 with Calendar.MONTH as fragment will return 28 * (equivalent to calendar.get(Calendar.DAY_OF_MONTH))
  • *
  • February 28, 2008 with Calendar.MONTH as fragment will return 28 * (equivalent to calendar.get(Calendar.DAY_OF_MONTH))
  • *
  • January 28, 2008 with Calendar.YEAR as fragment will return 28 * (equivalent to calendar.get(Calendar.DAY_OF_YEAR))
  • *
  • February 28, 2008 with Calendar.YEAR as fragment will return 59 * (equivalent to calendar.get(Calendar.DAY_OF_YEAR))
  • *
  • January 28, 2008 with Calendar.MILLISECOND as fragment will return 0 * (a millisecond cannot be split in days)
  • *
*

  * 
  * @param calendar the calendar to work with, not null
  * @param fragment the Calendar field part of calendar to calculate 
  * @return number of days within the fragment of date
  * @throws IllegalArgumentException if the date is null or 
  * fragment is not supported
  * @since 2.4
  */
 public static long getFragmentInDays(Calendar calendar, int fragment) {
     return getFragment(calendar, fragment, Calendar.DAY_OF_YEAR);
 }
 
 
 /**
  * Date-version for fragment-calculation in any unit
  * 
  * @param date the date to work with, not null
  * @param fragment the Calendar field part of date to calculate 
  * @param unit Calendar field defining the unit
  * @return number of units within the fragment of the date
  * @throws IllegalArgumentException if the date is null or 
  * fragment is not supported
  * @since 2.4
  */
 private static long getFragment(Date date, int fragment, int unit) {
     if(date == null) {
         throw  new IllegalArgumentException("The date must not be null");
     }
     Calendar calendar = Calendar.getInstance();
     calendar.setTime(date);
     return getFragment(calendar, fragment, unit);
 }
 /**
  * Calendar-version for fragment-calculation in any unit
  * 
  * @param calendar the calendar to work with, not null
  * @param fragment the Calendar field part of calendar to calculate 
  * @param unit Calendar field defining the unit
  * @return number of units within the fragment of the calendar
  * @throws IllegalArgumentException if the date is null or 
  * fragment is not supported
  * @since 2.4
  */
 private static long getFragment(Calendar calendar, int fragment, int unit) {
     if(calendar == null) {
         throw  new IllegalArgumentException("The date must not be null"); 
     }
     long millisPerUnit = getMillisPerUnit(unit);
     long result = 0;
     
     // Fragments bigger than a day require a breakdown to days
     switch (fragment) {
         case Calendar.YEAR:
             result += (calendar.get(Calendar.DAY_OF_YEAR) * MILLIS_PER_DAY) / millisPerUnit;
             break;
         case Calendar.MONTH:
             result += (calendar.get(Calendar.DAY_OF_MONTH) * MILLIS_PER_DAY) / millisPerUnit;
             break;
     }
     switch (fragment) {
         // Number of days already calculated for these cases
         case Calendar.YEAR:
         case Calendar.MONTH:
         
         // The rest of the valid cases
         case Calendar.DAY_OF_YEAR:
         case Calendar.DATE:
             result += (calendar.get(Calendar.HOUR_OF_DAY) * MILLIS_PER_HOUR) / millisPerUnit;
         case Calendar.HOUR_OF_DAY:
             result += (calendar.get(Calendar.MINUTE) * MILLIS_PER_MINUTE) / millisPerUnit;
         case Calendar.MINUTE:
             result += (calendar.get(Calendar.SECOND) * MILLIS_PER_SECOND) / millisPerUnit;
         case Calendar.SECOND:
             result += (calendar.get(Calendar.MILLISECOND) * 1) / millisPerUnit;
             break;
         case Calendar.MILLISECOND: break;//never useful
             default: throw new IllegalArgumentException("The fragment " + fragment + " is not supported");
     }
     return result;
 }
 /**
  * Returns the number of millis of a datefield, if this is a constant value
  * 
  * @param unit A Calendar field which is a valid unit for a fragment
  * @return number of millis
  * @throws IllegalArgumentException if date can"t be represented in millisenconds
  * @since 2.4 
  */
 private static long getMillisPerUnit(int unit) {
     long result = Long.MAX_VALUE;
     switch (unit) {
         case Calendar.DAY_OF_YEAR:
         case Calendar.DATE:
             result = MILLIS_PER_DAY;
             break;
         case Calendar.HOUR_OF_DAY:
             result = MILLIS_PER_HOUR;
             break;
         case Calendar.MINUTE:
             result = MILLIS_PER_MINUTE;
             break;
         case Calendar.SECOND:
             result = MILLIS_PER_SECOND;
             break;
         case Calendar.MILLISECOND:
             result = 1;
             break;
         default: throw new IllegalArgumentException("The unit " + unit + " cannot be represented is milleseconds");
     }
     return result;
 }

}


 </source>
   
  
 
  



Returns the number of hours within the fragment.

   <source lang="java">
 

import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.TimeZone;

/**

* 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 {

 /**
  * The UTC time zone  (often referred to as GMT).
  */
 public static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("GMT");
 /**
  * Number of milliseconds in a standard second.
  * @since 2.1
  */
 public static final long MILLIS_PER_SECOND = 1000;
 /**
  * Number of milliseconds in a standard minute.
  * @since 2.1
  */
 public static final long MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND;
 /**
  * Number of milliseconds in a standard hour.
  * @since 2.1
  */
 public static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE;
 /**
  * Number of milliseconds in a standard day.
  * @since 2.1
  */
 public static final long MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR;
 /**
  * This is half a month, so this represents whether a date is in the top
  * or bottom half of the month.
  */
 public final static int SEMI_MONTH = 1001;
 private static final int[][] fields = {
         {Calendar.MILLISECOND},
         {Calendar.SECOND},
         {Calendar.MINUTE},
         {Calendar.HOUR_OF_DAY, Calendar.HOUR},
         {Calendar.DATE, Calendar.DAY_OF_MONTH, Calendar.AM_PM 
             /* Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK, Calendar.DAY_OF_WEEK_IN_MONTH */
         },
         {Calendar.MONTH, DateUtils.SEMI_MONTH},
         {Calendar.YEAR},
         {Calendar.ERA}};
 /**
  * A week range, starting on Sunday.
  */
 public final static int RANGE_WEEK_SUNDAY = 1;
 /**
  * A week range, starting on Monday.
  */
 public final static int RANGE_WEEK_MONDAY = 2;
 /**
  * A week range, starting on the day focused.
  */
 public final static int RANGE_WEEK_RELATIVE = 3;
 /**
  * A week range, centered around the day focused.
  */
 public final static int RANGE_WEEK_CENTER = 4;
 /**
  * A month range, the week starting on Sunday.
  */
 public final static int RANGE_MONTH_SUNDAY = 5;
 /**
  * A month range, the week starting on Monday.
  */
 public final static int RANGE_MONTH_MONDAY = 6;
 
 
 /**
*

Returns the number of hours within the * fragment. All datefields greater than the fragment will be ignored.

  * 
*

Asking the hours of any date will only return the number of hours * of the current day (resulting in a number between 0 and 23). This * method will retrieve the number of hours for any fragment. * For example, if you want to calculate the number of hours past this month, * your fragment is Calendar.MONTH. The result will be all hours of the * past day(s).

  * 
*

Valid fragments are: Calendar.YEAR, Calendar.MONTH, both * Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY, * Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND * A fragment less than or equal to a HOUR field will return 0.

  * 
*

*

    *
  • January 1, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will return 7 * (equivalent to deprecated date.getHours())
  • *
  • January 6, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will return 7 * (equivalent to deprecated date.getHours())
  • *
  • January 1, 2008 7:15:10.538 with Calendar.MONTH as fragment will return 7
  • *
  • January 6, 2008 7:15:10.538 with Calendar.MONTH as fragment will return 127 (5*24 + 7)
  • *
  • January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will return 0 * (a millisecond cannot be split in hours)
  • *
*

  * 
  * @param date the date to work with, not null
  * @param fragment the Calendar field part of date to calculate 
  * @return number of hours within the fragment of date
  * @throws IllegalArgumentException if the date is null or 
  * fragment is not supported
  * @since 2.4
  */
 public static long getFragmentInHours(Date date, int fragment) {
     return getFragment(date, fragment, Calendar.HOUR_OF_DAY);
 }
 
 
 
 /**
  * Date-version for fragment-calculation in any unit
  * 
  * @param date the date to work with, not null
  * @param fragment the Calendar field part of date to calculate 
  * @param unit Calendar field defining the unit
  * @return number of units within the fragment of the date
  * @throws IllegalArgumentException if the date is null or 
  * fragment is not supported
  * @since 2.4
  */
 private static long getFragment(Date date, int fragment, int unit) {
     if(date == null) {
         throw  new IllegalArgumentException("The date must not be null");
     }
     Calendar calendar = Calendar.getInstance();
     calendar.setTime(date);
     return getFragment(calendar, fragment, unit);
 }
 /**
  * Calendar-version for fragment-calculation in any unit
  * 
  * @param calendar the calendar to work with, not null
  * @param fragment the Calendar field part of calendar to calculate 
  * @param unit Calendar field defining the unit
  * @return number of units within the fragment of the calendar
  * @throws IllegalArgumentException if the date is null or 
  * fragment is not supported
  * @since 2.4
  */
 private static long getFragment(Calendar calendar, int fragment, int unit) {
     if(calendar == null) {
         throw  new IllegalArgumentException("The date must not be null"); 
     }
     long millisPerUnit = getMillisPerUnit(unit);
     long result = 0;
     
     // Fragments bigger than a day require a breakdown to days
     switch (fragment) {
         case Calendar.YEAR:
             result += (calendar.get(Calendar.DAY_OF_YEAR) * MILLIS_PER_DAY) / millisPerUnit;
             break;
         case Calendar.MONTH:
             result += (calendar.get(Calendar.DAY_OF_MONTH) * MILLIS_PER_DAY) / millisPerUnit;
             break;
     }
     switch (fragment) {
         // Number of days already calculated for these cases
         case Calendar.YEAR:
         case Calendar.MONTH:
         
         // The rest of the valid cases
         case Calendar.DAY_OF_YEAR:
         case Calendar.DATE:
             result += (calendar.get(Calendar.HOUR_OF_DAY) * MILLIS_PER_HOUR) / millisPerUnit;
         case Calendar.HOUR_OF_DAY:
             result += (calendar.get(Calendar.MINUTE) * MILLIS_PER_MINUTE) / millisPerUnit;
         case Calendar.MINUTE:
             result += (calendar.get(Calendar.SECOND) * MILLIS_PER_SECOND) / millisPerUnit;
         case Calendar.SECOND:
             result += (calendar.get(Calendar.MILLISECOND) * 1) / millisPerUnit;
             break;
         case Calendar.MILLISECOND: break;//never useful
             default: throw new IllegalArgumentException("The fragment " + fragment + " is not supported");
     }
     return result;
 }
 /**
  * Returns the number of millis of a datefield, if this is a constant value
  * 
  * @param unit A Calendar field which is a valid unit for a fragment
  * @return number of millis
  * @throws IllegalArgumentException if date can"t be represented in millisenconds
  * @since 2.4 
  */
 private static long getMillisPerUnit(int unit) {
     long result = Long.MAX_VALUE;
     switch (unit) {
         case Calendar.DAY_OF_YEAR:
         case Calendar.DATE:
             result = MILLIS_PER_DAY;
             break;
         case Calendar.HOUR_OF_DAY:
             result = MILLIS_PER_HOUR;
             break;
         case Calendar.MINUTE:
             result = MILLIS_PER_MINUTE;
             break;
         case Calendar.SECOND:
             result = MILLIS_PER_SECOND;
             break;
         case Calendar.MILLISECOND:
             result = 1;
             break;
         default: throw new IllegalArgumentException("The unit " + unit + " cannot be represented is milleseconds");
     }
     return result;
 }

}


 </source>
   
  
 
  



Returns the number of milliseconds within the fragment.

   <source lang="java">
 

import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.TimeZone;

/**

* 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 {

 /**
  * The UTC time zone  (often referred to as GMT).
  */
 public static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("GMT");
 /**
  * Number of milliseconds in a standard second.
  * @since 2.1
  */
 public static final long MILLIS_PER_SECOND = 1000;
 /**
  * Number of milliseconds in a standard minute.
  * @since 2.1
  */
 public static final long MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND;
 /**
  * Number of milliseconds in a standard hour.
  * @since 2.1
  */
 public static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE;
 /**
  * Number of milliseconds in a standard day.
  * @since 2.1
  */
 public static final long MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR;
 /**
  * This is half a month, so this represents whether a date is in the top
  * or bottom half of the month.
  */
 public final static int SEMI_MONTH = 1001;
 private static final int[][] fields = {
         {Calendar.MILLISECOND},
         {Calendar.SECOND},
         {Calendar.MINUTE},
         {Calendar.HOUR_OF_DAY, Calendar.HOUR},
         {Calendar.DATE, Calendar.DAY_OF_MONTH, Calendar.AM_PM 
             /* Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK, Calendar.DAY_OF_WEEK_IN_MONTH */
         },
         {Calendar.MONTH, DateUtils.SEMI_MONTH},
         {Calendar.YEAR},
         {Calendar.ERA}};
 /**
  * A week range, starting on Sunday.
  */
 public final static int RANGE_WEEK_SUNDAY = 1;
 /**
  * A week range, starting on Monday.
  */
 public final static int RANGE_WEEK_MONDAY = 2;
 /**
  * A week range, starting on the day focused.
  */
 public final static int RANGE_WEEK_RELATIVE = 3;
 /**
  * A week range, centered around the day focused.
  */
 public final static int RANGE_WEEK_CENTER = 4;
 /**
  * A month range, the week starting on Sunday.
  */
 public final static int RANGE_MONTH_SUNDAY = 5;
 /**
  * A month range, the week starting on Monday.
  */
 public final static int RANGE_MONTH_MONDAY = 6;
 
 /**
*

Returns the number of milliseconds within the * fragment. All datefields greater than the fragment will be ignored.

  * 
*

Asking the milliseconds of any date will only return the number of milliseconds * of the current second (resulting in a number between 0 and 999). This * method will retrieve the number of milliseconds for any fragment. * For example, if you want to calculate the number of seconds past today, * your fragment is Calendar.DATE or Calendar.DAY_OF_YEAR. The result will * be all seconds of the past hour(s), minutes(s) and second(s).

  * 
*

Valid fragments are: Calendar.YEAR, Calendar.MONTH, both * Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY, * Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND * A fragment less than or equal to a MILLISECOND field will return 0.

  * 
*

*

    *
  • January 1, 2008 7:15:10.538 with Calendar.SECOND as fragment will return 538 * (equivalent to calendar.get(Calendar.MILLISECOND))
  • *
  • January 6, 2008 7:15:10.538 with Calendar.SECOND as fragment will return 538 * (equivalent to calendar.get(Calendar.MILLISECOND))
  • *
  • January 6, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return 10538 * (10*1000 + 538)
  • *
  • January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will return 0 * (a millisecond cannot be split in milliseconds)
  • *
*

  * 
  * @param calendar the calendar to work with, not null
  * @param fragment the Calendar field part of calendar to calculate 
  * @return number of milliseconds within the fragment of date
  * @throws IllegalArgumentException if the date is null or 
  * fragment is not supported
  * @since 2.4
  */

public static long getFragmentInMilliseconds(Calendar calendar, int fragment) {

 return getFragment(calendar, fragment, Calendar.MILLISECOND);

}

 /**
  * Date-version for fragment-calculation in any unit
  * 
  * @param date the date to work with, not null
  * @param fragment the Calendar field part of date to calculate 
  * @param unit Calendar field defining the unit
  * @return number of units within the fragment of the date
  * @throws IllegalArgumentException if the date is null or 
  * fragment is not supported
  * @since 2.4
  */
 private static long getFragment(Date date, int fragment, int unit) {
     if(date == null) {
         throw  new IllegalArgumentException("The date must not be null");
     }
     Calendar calendar = Calendar.getInstance();
     calendar.setTime(date);
     return getFragment(calendar, fragment, unit);
 }
 /**
  * Calendar-version for fragment-calculation in any unit
  * 
  * @param calendar the calendar to work with, not null
  * @param fragment the Calendar field part of calendar to calculate 
  * @param unit Calendar field defining the unit
  * @return number of units within the fragment of the calendar
  * @throws IllegalArgumentException if the date is null or 
  * fragment is not supported
  * @since 2.4
  */
 private static long getFragment(Calendar calendar, int fragment, int unit) {
     if(calendar == null) {
         throw  new IllegalArgumentException("The date must not be null"); 
     }
     long millisPerUnit = getMillisPerUnit(unit);
     long result = 0;
     
     // Fragments bigger than a day require a breakdown to days
     switch (fragment) {
         case Calendar.YEAR:
             result += (calendar.get(Calendar.DAY_OF_YEAR) * MILLIS_PER_DAY) / millisPerUnit;
             break;
         case Calendar.MONTH:
             result += (calendar.get(Calendar.DAY_OF_MONTH) * MILLIS_PER_DAY) / millisPerUnit;
             break;
     }
     switch (fragment) {
         // Number of days already calculated for these cases
         case Calendar.YEAR:
         case Calendar.MONTH:
         
         // The rest of the valid cases
         case Calendar.DAY_OF_YEAR:
         case Calendar.DATE:
             result += (calendar.get(Calendar.HOUR_OF_DAY) * MILLIS_PER_HOUR) / millisPerUnit;
         case Calendar.HOUR_OF_DAY:
             result += (calendar.get(Calendar.MINUTE) * MILLIS_PER_MINUTE) / millisPerUnit;
         case Calendar.MINUTE:
             result += (calendar.get(Calendar.SECOND) * MILLIS_PER_SECOND) / millisPerUnit;
         case Calendar.SECOND:
             result += (calendar.get(Calendar.MILLISECOND) * 1) / millisPerUnit;
             break;
         case Calendar.MILLISECOND: break;//never useful
             default: throw new IllegalArgumentException("The fragment " + fragment + " is not supported");
     }
     return result;
 }
 /**
  * Returns the number of millis of a datefield, if this is a constant value
  * 
  * @param unit A Calendar field which is a valid unit for a fragment
  * @return number of millis
  * @throws IllegalArgumentException if date can"t be represented in millisenconds
  * @since 2.4 
  */
 private static long getMillisPerUnit(int unit) {
     long result = Long.MAX_VALUE;
     switch (unit) {
         case Calendar.DAY_OF_YEAR:
         case Calendar.DATE:
             result = MILLIS_PER_DAY;
             break;
         case Calendar.HOUR_OF_DAY:
             result = MILLIS_PER_HOUR;
             break;
         case Calendar.MINUTE:
             result = MILLIS_PER_MINUTE;
             break;
         case Calendar.SECOND:
             result = MILLIS_PER_SECOND;
             break;
         case Calendar.MILLISECOND:
             result = 1;
             break;
         default: throw new IllegalArgumentException("The unit " + unit + " cannot be represented is milleseconds");
     }
     return result;
 }

}


 </source>
   
  
 
  



Returns the number of minutes within the fragment.

   <source lang="java">
 

import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.TimeZone;

/**

* 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 {

 /**
  * The UTC time zone  (often referred to as GMT).
  */
 public static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("GMT");
 /**
  * Number of milliseconds in a standard second.
  * @since 2.1
  */
 public static final long MILLIS_PER_SECOND = 1000;
 /**
  * Number of milliseconds in a standard minute.
  * @since 2.1
  */
 public static final long MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND;
 /**
  * Number of milliseconds in a standard hour.
  * @since 2.1
  */
 public static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE;
 /**
  * Number of milliseconds in a standard day.
  * @since 2.1
  */
 public static final long MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR;
 /**
  * This is half a month, so this represents whether a date is in the top
  * or bottom half of the month.
  */
 public final static int SEMI_MONTH = 1001;
 private static final int[][] fields = {
         {Calendar.MILLISECOND},
         {Calendar.SECOND},
         {Calendar.MINUTE},
         {Calendar.HOUR_OF_DAY, Calendar.HOUR},
         {Calendar.DATE, Calendar.DAY_OF_MONTH, Calendar.AM_PM 
             /* Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK, Calendar.DAY_OF_WEEK_IN_MONTH */
         },
         {Calendar.MONTH, DateUtils.SEMI_MONTH},
         {Calendar.YEAR},
         {Calendar.ERA}};
 /**
  * A week range, starting on Sunday.
  */
 public final static int RANGE_WEEK_SUNDAY = 1;
 /**
  * A week range, starting on Monday.
  */
 public final static int RANGE_WEEK_MONDAY = 2;
 /**
  * A week range, starting on the day focused.
  */
 public final static int RANGE_WEEK_RELATIVE = 3;
 /**
  * A week range, centered around the day focused.
  */
 public final static int RANGE_WEEK_CENTER = 4;
 /**
  * A month range, the week starting on Sunday.
  */
 public final static int RANGE_MONTH_SUNDAY = 5;
 /**
  * A month range, the week starting on Monday.
  */
 public final static int RANGE_MONTH_MONDAY = 6;
 
 
 /**
*

Returns the number of minutes within the * fragment. All datefields greater than the fragment will be ignored.

  * 
*

Asking the minutes of any date will only return the number of minutes * of the current hour (resulting in a number between 0 and 59). This * method will retrieve the number of minutes for any fragment. * For example, if you want to calculate the number of minutes past this month, * your fragment is Calendar.MONTH. The result will be all minutes of the * past day(s) and hour(s).

  * 
*

Valid fragments are: Calendar.YEAR, Calendar.MONTH, both * Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY, * Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND * A fragment less than or equal to a MINUTE field will return 0.

  * 
*

*

    *
  • January 1, 2008 7:15:10.538 with Calendar.HOUR_OF_DAY as fragment will return 15 * (equivalent to deprecated date.getMinutes())
  • *
  • January 6, 2008 7:15:10.538 with Calendar.HOUR_OF_DAY as fragment will return 15 * (equivalent to deprecated date.getMinutes())
  • *
  • January 1, 2008 7:15:10.538 with Calendar.MONTH as fragment will return 15
  • *
  • January 6, 2008 7:15:10.538 with Calendar.MONTH as fragment will return 435 (7*60 + 15)
  • *
  • January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will return 0 * (a millisecond cannot be split in minutes)
  • *
*

  * 
  * @param date the date to work with, not null
  * @param fragment the Calendar field part of date to calculate 
  * @return number of minutes within the fragment of date
  * @throws IllegalArgumentException if the date is null or 
  * fragment is not supported
  * @since 2.4
  */
 public static long getFragmentInMinutes(Date date, int fragment) {
     return getFragment(date, fragment, Calendar.MINUTE);
 }
 
 
 /**
  * Date-version for fragment-calculation in any unit
  * 
  * @param date the date to work with, not null
  * @param fragment the Calendar field part of date to calculate 
  * @param unit Calendar field defining the unit
  * @return number of units within the fragment of the date
  * @throws IllegalArgumentException if the date is null or 
  * fragment is not supported
  * @since 2.4
  */
 private static long getFragment(Date date, int fragment, int unit) {
     if(date == null) {
         throw  new IllegalArgumentException("The date must not be null");
     }
     Calendar calendar = Calendar.getInstance();
     calendar.setTime(date);
     return getFragment(calendar, fragment, unit);
 }
 /**
  * Calendar-version for fragment-calculation in any unit
  * 
  * @param calendar the calendar to work with, not null
  * @param fragment the Calendar field part of calendar to calculate 
  * @param unit Calendar field defining the unit
  * @return number of units within the fragment of the calendar
  * @throws IllegalArgumentException if the date is null or 
  * fragment is not supported
  * @since 2.4
  */
 private static long getFragment(Calendar calendar, int fragment, int unit) {
     if(calendar == null) {
         throw  new IllegalArgumentException("The date must not be null"); 
     }
     long millisPerUnit = getMillisPerUnit(unit);
     long result = 0;
     
     // Fragments bigger than a day require a breakdown to days
     switch (fragment) {
         case Calendar.YEAR:
             result += (calendar.get(Calendar.DAY_OF_YEAR) * MILLIS_PER_DAY) / millisPerUnit;
             break;
         case Calendar.MONTH:
             result += (calendar.get(Calendar.DAY_OF_MONTH) * MILLIS_PER_DAY) / millisPerUnit;
             break;
     }
     switch (fragment) {
         // Number of days already calculated for these cases
         case Calendar.YEAR:
         case Calendar.MONTH:
         
         // The rest of the valid cases
         case Calendar.DAY_OF_YEAR:
         case Calendar.DATE:
             result += (calendar.get(Calendar.HOUR_OF_DAY) * MILLIS_PER_HOUR) / millisPerUnit;
         case Calendar.HOUR_OF_DAY:
             result += (calendar.get(Calendar.MINUTE) * MILLIS_PER_MINUTE) / millisPerUnit;
         case Calendar.MINUTE:
             result += (calendar.get(Calendar.SECOND) * MILLIS_PER_SECOND) / millisPerUnit;
         case Calendar.SECOND:
             result += (calendar.get(Calendar.MILLISECOND) * 1) / millisPerUnit;
             break;
         case Calendar.MILLISECOND: break;//never useful
             default: throw new IllegalArgumentException("The fragment " + fragment + " is not supported");
     }
     return result;
 }
 /**
  * Returns the number of millis of a datefield, if this is a constant value
  * 
  * @param unit A Calendar field which is a valid unit for a fragment
  * @return number of millis
  * @throws IllegalArgumentException if date can"t be represented in millisenconds
  * @since 2.4 
  */
 private static long getMillisPerUnit(int unit) {
     long result = Long.MAX_VALUE;
     switch (unit) {
         case Calendar.DAY_OF_YEAR:
         case Calendar.DATE:
             result = MILLIS_PER_DAY;
             break;
         case Calendar.HOUR_OF_DAY:
             result = MILLIS_PER_HOUR;
             break;
         case Calendar.MINUTE:
             result = MILLIS_PER_MINUTE;
             break;
         case Calendar.SECOND:
             result = MILLIS_PER_SECOND;
             break;
         case Calendar.MILLISECOND:
             result = 1;
             break;
         default: throw new IllegalArgumentException("The unit " + unit + " cannot be represented is milleseconds");
     }
     return result;
 }

}


 </source>
   
  
 
  



Returns the number of seconds within the fragment.

   <source lang="java">
 

import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.TimeZone;

/**

* 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 {

 /**
  * The UTC time zone  (often referred to as GMT).
  */
 public static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("GMT");
 /**
  * Number of milliseconds in a standard second.
  * @since 2.1
  */
 public static final long MILLIS_PER_SECOND = 1000;
 /**
  * Number of milliseconds in a standard minute.
  * @since 2.1
  */
 public static final long MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND;
 /**
  * Number of milliseconds in a standard hour.
  * @since 2.1
  */
 public static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE;
 /**
  * Number of milliseconds in a standard day.
  * @since 2.1
  */
 public static final long MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR;
 /**
  * This is half a month, so this represents whether a date is in the top
  * or bottom half of the month.
  */
 public final static int SEMI_MONTH = 1001;
 private static final int[][] fields = {
         {Calendar.MILLISECOND},
         {Calendar.SECOND},
         {Calendar.MINUTE},
         {Calendar.HOUR_OF_DAY, Calendar.HOUR},
         {Calendar.DATE, Calendar.DAY_OF_MONTH, Calendar.AM_PM 
             /* Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK, Calendar.DAY_OF_WEEK_IN_MONTH */
         },
         {Calendar.MONTH, DateUtils.SEMI_MONTH},
         {Calendar.YEAR},
         {Calendar.ERA}};
 /**
  * A week range, starting on Sunday.
  */
 public final static int RANGE_WEEK_SUNDAY = 1;
 /**
  * A week range, starting on Monday.
  */
 public final static int RANGE_WEEK_MONDAY = 2;
 /**
  * A week range, starting on the day focused.
  */
 public final static int RANGE_WEEK_RELATIVE = 3;
 /**
  * A week range, centered around the day focused.
  */
 public final static int RANGE_WEEK_CENTER = 4;
 /**
  * A month range, the week starting on Sunday.
  */
 public final static int RANGE_MONTH_SUNDAY = 5;
 /**
  * A month range, the week starting on Monday.
  */
 public final static int RANGE_MONTH_MONDAY = 6;
 
 
 
 /**
*

Returns the number of seconds within the * fragment. All datefields greater than the fragment will be ignored.

  * 
*

Asking the seconds of any date will only return the number of seconds * of the current minute (resulting in a number between 0 and 59). This * method will retrieve the number of seconds for any fragment. * For example, if you want to calculate the number of seconds past today, * your fragment is Calendar.DATE or Calendar.DAY_OF_YEAR. The result will * be all seconds of the past hour(s) and minutes(s).

  * 
*

Valid fragments are: Calendar.YEAR, Calendar.MONTH, both * Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY, * Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND * A fragment less than or equal to a SECOND field will return 0.

  * 
*

*

    *
  • January 1, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return 10 * (equivalent to deprecated date.getSeconds())
  • *
  • January 6, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return 10 * (equivalent to deprecated date.getSeconds())
  • *
  • January 6, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will return 26110 * (7*3600 + 15*60 + 10)
  • *
  • January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will return 0 * (a millisecond cannot be split in seconds)
  • *
*

  * 
  * @param date the date to work with, not null
  * @param fragment the Calendar field part of date to calculate 
  * @return number of seconds within the fragment of date
  * @throws IllegalArgumentException if the date is null or
  * fragment is not supported
  * @since 2.4
  */
 public static long getFragmentInSeconds(Date date, int fragment) {
     return getFragment(date, fragment, Calendar.SECOND);
 }
 
 
 /**
  * Date-version for fragment-calculation in any unit
  * 
  * @param date the date to work with, not null
  * @param fragment the Calendar field part of date to calculate 
  * @param unit Calendar field defining the unit
  * @return number of units within the fragment of the date
  * @throws IllegalArgumentException if the date is null or 
  * fragment is not supported
  * @since 2.4
  */
 private static long getFragment(Date date, int fragment, int unit) {
     if(date == null) {
         throw  new IllegalArgumentException("The date must not be null");
     }
     Calendar calendar = Calendar.getInstance();
     calendar.setTime(date);
     return getFragment(calendar, fragment, unit);
 }
 /**
  * Calendar-version for fragment-calculation in any unit
  * 
  * @param calendar the calendar to work with, not null
  * @param fragment the Calendar field part of calendar to calculate 
  * @param unit Calendar field defining the unit
  * @return number of units within the fragment of the calendar
  * @throws IllegalArgumentException if the date is null or 
  * fragment is not supported
  * @since 2.4
  */
 private static long getFragment(Calendar calendar, int fragment, int unit) {
     if(calendar == null) {
         throw  new IllegalArgumentException("The date must not be null"); 
     }
     long millisPerUnit = getMillisPerUnit(unit);
     long result = 0;
     
     // Fragments bigger than a day require a breakdown to days
     switch (fragment) {
         case Calendar.YEAR:
             result += (calendar.get(Calendar.DAY_OF_YEAR) * MILLIS_PER_DAY) / millisPerUnit;
             break;
         case Calendar.MONTH:
             result += (calendar.get(Calendar.DAY_OF_MONTH) * MILLIS_PER_DAY) / millisPerUnit;
             break;
     }
     switch (fragment) {
         // Number of days already calculated for these cases
         case Calendar.YEAR:
         case Calendar.MONTH:
         
         // The rest of the valid cases
         case Calendar.DAY_OF_YEAR:
         case Calendar.DATE:
             result += (calendar.get(Calendar.HOUR_OF_DAY) * MILLIS_PER_HOUR) / millisPerUnit;
         case Calendar.HOUR_OF_DAY:
             result += (calendar.get(Calendar.MINUTE) * MILLIS_PER_MINUTE) / millisPerUnit;
         case Calendar.MINUTE:
             result += (calendar.get(Calendar.SECOND) * MILLIS_PER_SECOND) / millisPerUnit;
         case Calendar.SECOND:
             result += (calendar.get(Calendar.MILLISECOND) * 1) / millisPerUnit;
             break;
         case Calendar.MILLISECOND: break;//never useful
             default: throw new IllegalArgumentException("The fragment " + fragment + " is not supported");
     }
     return result;
 }
 /**
  * Returns the number of millis of a datefield, if this is a constant value
  * 
  * @param unit A Calendar field which is a valid unit for a fragment
  * @return number of millis
  * @throws IllegalArgumentException if date can"t be represented in millisenconds
  * @since 2.4 
  */
 private static long getMillisPerUnit(int unit) {
     long result = Long.MAX_VALUE;
     switch (unit) {
         case Calendar.DAY_OF_YEAR:
         case Calendar.DATE:
             result = MILLIS_PER_DAY;
             break;
         case Calendar.HOUR_OF_DAY:
             result = MILLIS_PER_HOUR;
             break;
         case Calendar.MINUTE:
             result = MILLIS_PER_MINUTE;
             break;
         case Calendar.SECOND:
             result = MILLIS_PER_SECOND;
             break;
         case Calendar.MILLISECOND:
             result = 1;
             break;
         default: throw new IllegalArgumentException("The unit " + unit + " cannot be represented is milleseconds");
     }
     return result;
 }

}


 </source>
   
  
 
  



Returns true if endDate is after startDate or if startDate equals endDate.

   <source lang="java">
 

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
*  contributor license agreements.  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.  For additional information regarding
* copyright in this work, please see the NOTICE file in the top level
* directory of this distribution.
*/

import java.util.Date; public class Utils {

 /**
  * Returns true if endDate is after startDate or if startDate equals endDate.
  * Returns false if either value is null.  If equalOK, returns true if the
  * dates are equal.
  **/
 public static boolean isValidDateRange(Date startDate, Date endDate, boolean equalOK) {
     // false if either value is null
     if (startDate == null || endDate == null) { return false; }
     
     if (equalOK) {
         // true if they are equal
         if (startDate.equals(endDate)) { return true; }
     }
     
     // true if endDate after startDate
     if (endDate.after(startDate)) { return true; }
     
     return false;
 }

}


 </source>
   
  
 
  



Roll the days forward or backward

   <source lang="java">
  

/*

* Copyright Javelin Software, All rights reserved.
*/

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

* The DateUtil is used as a Utility Class for Dates.
* 
* @author Robin Sharp
*/

public class DateUtil {

   public final static long SECOND_MILLIS = 1000;
   public final static long MINUTE_MILLIS = SECOND_MILLIS*60;
   public final static long HOUR_MILLIS = MINUTE_MILLIS*60;
   public final static long DAY_MILLIS = HOUR_MILLIS*24;
   public final static long YEAR_MILLIS = DAY_MILLIS*365;
   public static DateFormat OUT_DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy");
   public static DateFormat OUT_TIME_FORMAT = new SimpleDateFormat("H:mm:ss");
   public static DateFormat OUT_DATETIME_FORMAT = new SimpleDateFormat("d/M/yyyy H:mm:ss");
   public static DateFormat OUT_TIMESTAMP_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss.SSS");
   
   public static DateFormat IN_DATE_FORMAT = new SimpleDateFormat("d/M/yy");
   public static DateFormat IN_TIME_FORMAT = new SimpleDateFormat("H:mm:ss");
   public static DateFormat IN_DATETIME_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss");
   public static DateFormat IN_TIMESTAMP_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss.SSS");
   
   public static DateFormat DATE_TIME_FORMAT= new SimpleDateFormat( "yyyyMMddkkmmss" );  
   public static Calendar calendar = new GregorianCalendar();
   static
   {
       IN_DATE_FORMAT.setLenient(false);
       IN_TIME_FORMAT.setLenient(false);
       IN_DATETIME_FORMAT.setLenient(false);
   }
   /**
    * Create a new DateTime. To the last second. This will not create any 
    * extra-millis-seconds, which may cause bugs when writing to stores such as
    * databases that round milli-seconds up and down. 
    */
   public static java.util.Date newDateTime()
   {
       return new java.util.Date( (System.currentTimeMillis()/SECOND_MILLIS)*SECOND_MILLIS);
   }
   /**
    * Create a new Date. To the last day.
    */
   public static java.sql.Date newDate()
   {
       return new java.sql.Date( (System.currentTimeMillis()/DAY_MILLIS)*DAY_MILLIS);
   }
   
   /**
    * Create a new Time, with no date component. 
    */
   public static java.sql.Time newTime()
   {
       return new java.sql.Time( System.currentTimeMillis()%DAY_MILLIS);
   }
   
   /**
    * Create a new Timestamp. 
    */
   public static java.sql.Timestamp newTimestamp()
   {
       return new java.sql.Timestamp( System.currentTimeMillis() );
   }
   
   /**
    * Get the seconds difference
    */
   public static int secondsDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/SECOND_MILLIS) - (earlierDate.getTime()/SECOND_MILLIS));
   }
   /**
    * Get the minutes difference
    */
   public static int minutesDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/MINUTE_MILLIS) - (earlierDate.getTime()/MINUTE_MILLIS));
   }
   
   /**
    * Get the hours difference
    */
   public static int hoursDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/HOUR_MILLIS) - (earlierDate.getTime()/HOUR_MILLIS));
   }
   
   /**
    * Get the days difference
    */
   public static int daysDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/DAY_MILLIS) - (earlierDate.getTime()/DAY_MILLIS));
   }
   
  /**
   * Roll the java.util.Time forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.sql.Time rollTime( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.sql.Time(gc.getTime().getTime());
   }
   
  /**
   * Roll the java.util.Date forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.util.Date rollDateTime( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.util.Date(gc.getTime().getTime());
   }
   
  /**
   * Roll the java.sql.Date forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.sql.Date rollDate( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.sql.Date(gc.getTime().getTime());
   }
   
  /**
   * Roll the years forward or backward.
   * @param startDate - The start date
   * @param years - Negative to rollbackwards.
   */
   public static java.sql.Date rollYears( java.util.Date startDate, int years )
   {
       return rollDate( startDate, Calendar.YEAR, years );
   }
  /**
   * Roll the days forward or backward.
   * @param startDate - The start date
   * @param months - Negative to rollbackwards.
   */
   public static java.sql.Date rollMonths( java.util.Date startDate, int months )
   {
       return rollDate( startDate, Calendar.MONTH, months );
   }
  /**
   * Roll the days forward or backward.
   * @param startDate - The start date
   * @param days - Negative to rollbackwards.
   */
   public static java.sql.Date rollDays( java.util.Date startDate, int days )
   {
       return rollDate( startDate, Calendar.DATE, days );
   }
   
    /**
     * Checks the day, month and year are equal.
     */
    public static boolean dateEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;
       
       return d1.getDate() == d2.getDate() &&
              d1.getMonth() == d2.getMonth() &&
              d1.getYear() == d2.getYear();
    }
    
    /**
     * Checks the hour, minute and second are equal.
     */
    public static boolean timeEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;
       
       return d1.getHours() == d2.getHours() &&
              d1.getMinutes() == d2.getMinutes() &&
              d1.getSeconds() == d2.getSeconds();
    }
   /**
     * Checks the second, hour, month, day, month and year are equal.
     */
    public static boolean dateTimeEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;               
       
       return d1.getDate() == d2.getDate() &&
              d1.getMonth() == d2.getMonth() &&
              d1.getYear() == d2.getYear() &&
              d1.getHours() == d2.getHours() &&
              d1.getMinutes() == d2.getMinutes() &&
              d1.getSeconds() == d2.getSeconds();
    }
    
    /**
    * Convert an Object of type Classs to an Object.
    */
   public static Object toObject( Class clazz, Object value ) throws ParseException
   {
       if( value == null ) return null;
       if( clazz == null ) return value;
       
       if( java.sql.Date.class.isAssignableFrom( clazz ) ) return toDate( value );
       if( java.sql.Time.class.isAssignableFrom( clazz ) ) return toTime( value );
       if( java.sql.Timestamp.class.isAssignableFrom( clazz ) ) return toTimestamp( value );
       if( java.util.Date.class.isAssignableFrom( clazz ) ) return toDateTime( value );
       
       return value;
   }
   
   /**
    * Convert an Object to a DateTime, without an Exception
    */
   public static java.util.Date getDateTime( Object value )
   {
       try
       {
           return toDateTime( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   
   /**
    * Convert an Object to a DateTime.
    */
   public static java.util.Date toDateTime( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.util.Date ) return (java.util.Date)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return IN_DATETIME_FORMAT.parse( (String)value );
       }
               
       return IN_DATETIME_FORMAT.parse( value.toString() );
   }
   
   /**
    * Convert an Object to a Date, without an Exception
    */
   public static java.sql.Date getDate( Object value )
   {
       try
       {
           return toDate( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   /**
    * Convert an Object to a Date.
    */
   public static java.sql.Date toDate( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Date ) return (java.sql.Date)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Date( IN_DATE_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Date( IN_DATE_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Convert an Object to a Time, without an Exception
    */
   public static java.sql.Time getTime( Object value )
   {
       try
       {
           return toTime( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   
   /**
    * Convert an Object to a Time.
    */
   public static java.sql.Time toTime( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Time ) return (java.sql.Time)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Time( IN_TIME_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Time( IN_TIME_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Convert an Object to a Timestamp, without an Exception
    */
   public static java.sql.Timestamp getTimestamp( Object value )
   {
       try
       {
           return toTimestamp( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   /**
    * Convert an Object to a Timestamp.
    */
   public static java.sql.Timestamp toTimestamp( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Timestamp ) return (java.sql.Timestamp)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Timestamp( IN_TIMESTAMP_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Timestamp( IN_TIMESTAMP_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Tells you if the date part of a datetime is in a certain time range.
    */
   public static boolean isTimeInRange( java.sql.Time start, java.sql.Time end, java.util.Date d )
   {
       d=new java.sql.Time(d.getHours(),d.getMinutes(),d.getSeconds());
       
       if (start==null || end==null)
       {
           return false;
       }
       
       if (start.before(end)&&(!(d.after(start)&&d.before(end))))
       {
           return false;
       }
       
       if (end.before(start)&&(!(d.after(end)||d.before(start))))
       {
           return false;
       }   
       return true;
   }
   public static  int getYear( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.YEAR );
   }
   public static int getMonth( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MONTH );
   }
   public static int getDate( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.DATE );
   }
   public static int getHour( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.HOUR );
   }
   public static int getMinute( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MINUTE );
   }
   public static int getSeconds( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.SECOND );
   }
   public static int getMillisecond( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MILLISECOND );
   }
   
   /**
    * Convert an Object to a String using Dates
    */
   public static String toString( Object date )
   {
       if( date == null ) return null;
       
       if( java.sql.Timestamp.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_TIMESTAMP_FORMAT.format( date );
       }
       if( java.sql.Time.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_TIME_FORMAT.format( date );
       }
       if( java.sql.Date.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_DATE_FORMAT.format( date );
       }
       if( java.util.Date.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_DATETIME_FORMAT.format( date );
       }
       
       throw new IllegalArgumentException( "Unsupported type " + date.getClass() );
   }

}


 </source>
   
  
 
  



Roll the java.sql.Date forward or backward

   <source lang="java">
  

/*

* Copyright Javelin Software, All rights reserved.
*/

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

* The DateUtil is used as a Utility Class for Dates.
* 
* @author Robin Sharp
*/

public class DateUtil {

   public final static long SECOND_MILLIS = 1000;
   public final static long MINUTE_MILLIS = SECOND_MILLIS*60;
   public final static long HOUR_MILLIS = MINUTE_MILLIS*60;
   public final static long DAY_MILLIS = HOUR_MILLIS*24;
   public final static long YEAR_MILLIS = DAY_MILLIS*365;
   public static DateFormat OUT_DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy");
   public static DateFormat OUT_TIME_FORMAT = new SimpleDateFormat("H:mm:ss");
   public static DateFormat OUT_DATETIME_FORMAT = new SimpleDateFormat("d/M/yyyy H:mm:ss");
   public static DateFormat OUT_TIMESTAMP_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss.SSS");
   
   public static DateFormat IN_DATE_FORMAT = new SimpleDateFormat("d/M/yy");
   public static DateFormat IN_TIME_FORMAT = new SimpleDateFormat("H:mm:ss");
   public static DateFormat IN_DATETIME_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss");
   public static DateFormat IN_TIMESTAMP_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss.SSS");
   
   public static DateFormat DATE_TIME_FORMAT= new SimpleDateFormat( "yyyyMMddkkmmss" );  
   public static Calendar calendar = new GregorianCalendar();
   static
   {
       IN_DATE_FORMAT.setLenient(false);
       IN_TIME_FORMAT.setLenient(false);
       IN_DATETIME_FORMAT.setLenient(false);
   }
   /**
    * Create a new DateTime. To the last second. This will not create any 
    * extra-millis-seconds, which may cause bugs when writing to stores such as
    * databases that round milli-seconds up and down. 
    */
   public static java.util.Date newDateTime()
   {
       return new java.util.Date( (System.currentTimeMillis()/SECOND_MILLIS)*SECOND_MILLIS);
   }
   /**
    * Create a new Date. To the last day.
    */
   public static java.sql.Date newDate()
   {
       return new java.sql.Date( (System.currentTimeMillis()/DAY_MILLIS)*DAY_MILLIS);
   }
   
   /**
    * Create a new Time, with no date component. 
    */
   public static java.sql.Time newTime()
   {
       return new java.sql.Time( System.currentTimeMillis()%DAY_MILLIS);
   }
   
   /**
    * Create a new Timestamp. 
    */
   public static java.sql.Timestamp newTimestamp()
   {
       return new java.sql.Timestamp( System.currentTimeMillis() );
   }
   
   /**
    * Get the seconds difference
    */
   public static int secondsDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/SECOND_MILLIS) - (earlierDate.getTime()/SECOND_MILLIS));
   }
   /**
    * Get the minutes difference
    */
   public static int minutesDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/MINUTE_MILLIS) - (earlierDate.getTime()/MINUTE_MILLIS));
   }
   
   /**
    * Get the hours difference
    */
   public static int hoursDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/HOUR_MILLIS) - (earlierDate.getTime()/HOUR_MILLIS));
   }
   
   /**
    * Get the days difference
    */
   public static int daysDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/DAY_MILLIS) - (earlierDate.getTime()/DAY_MILLIS));
   }
   
  /**
   * Roll the java.util.Time forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.sql.Time rollTime( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.sql.Time(gc.getTime().getTime());
   }
   
  /**
   * Roll the java.util.Date forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.util.Date rollDateTime( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.util.Date(gc.getTime().getTime());
   }
   
  /**
   * Roll the java.sql.Date forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.sql.Date rollDate( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.sql.Date(gc.getTime().getTime());
   }
   
  /**
   * Roll the years forward or backward.
   * @param startDate - The start date
   * @param years - Negative to rollbackwards.
   */
   public static java.sql.Date rollYears( java.util.Date startDate, int years )
   {
       return rollDate( startDate, Calendar.YEAR, years );
   }
  /**
   * Roll the days forward or backward.
   * @param startDate - The start date
   * @param months - Negative to rollbackwards.
   */
   public static java.sql.Date rollMonths( java.util.Date startDate, int months )
   {
       return rollDate( startDate, Calendar.MONTH, months );
   }
  /**
   * Roll the days forward or backward.
   * @param startDate - The start date
   * @param days - Negative to rollbackwards.
   */
   public static java.sql.Date rollDays( java.util.Date startDate, int days )
   {
       return rollDate( startDate, Calendar.DATE, days );
   }
   
    /**
     * Checks the day, month and year are equal.
     */
    public static boolean dateEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;
       
       return d1.getDate() == d2.getDate() &&
              d1.getMonth() == d2.getMonth() &&
              d1.getYear() == d2.getYear();
    }
    
    /**
     * Checks the hour, minute and second are equal.
     */
    public static boolean timeEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;
       
       return d1.getHours() == d2.getHours() &&
              d1.getMinutes() == d2.getMinutes() &&
              d1.getSeconds() == d2.getSeconds();
    }
   /**
     * Checks the second, hour, month, day, month and year are equal.
     */
    public static boolean dateTimeEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;               
       
       return d1.getDate() == d2.getDate() &&
              d1.getMonth() == d2.getMonth() &&
              d1.getYear() == d2.getYear() &&
              d1.getHours() == d2.getHours() &&
              d1.getMinutes() == d2.getMinutes() &&
              d1.getSeconds() == d2.getSeconds();
    }
    
    /**
    * Convert an Object of type Classs to an Object.
    */
   public static Object toObject( Class clazz, Object value ) throws ParseException
   {
       if( value == null ) return null;
       if( clazz == null ) return value;
       
       if( java.sql.Date.class.isAssignableFrom( clazz ) ) return toDate( value );
       if( java.sql.Time.class.isAssignableFrom( clazz ) ) return toTime( value );
       if( java.sql.Timestamp.class.isAssignableFrom( clazz ) ) return toTimestamp( value );
       if( java.util.Date.class.isAssignableFrom( clazz ) ) return toDateTime( value );
       
       return value;
   }
   
   /**
    * Convert an Object to a DateTime, without an Exception
    */
   public static java.util.Date getDateTime( Object value )
   {
       try
       {
           return toDateTime( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   
   /**
    * Convert an Object to a DateTime.
    */
   public static java.util.Date toDateTime( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.util.Date ) return (java.util.Date)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return IN_DATETIME_FORMAT.parse( (String)value );
       }
               
       return IN_DATETIME_FORMAT.parse( value.toString() );
   }
   
   /**
    * Convert an Object to a Date, without an Exception
    */
   public static java.sql.Date getDate( Object value )
   {
       try
       {
           return toDate( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   /**
    * Convert an Object to a Date.
    */
   public static java.sql.Date toDate( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Date ) return (java.sql.Date)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Date( IN_DATE_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Date( IN_DATE_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Convert an Object to a Time, without an Exception
    */
   public static java.sql.Time getTime( Object value )
   {
       try
       {
           return toTime( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   
   /**
    * Convert an Object to a Time.
    */
   public static java.sql.Time toTime( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Time ) return (java.sql.Time)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Time( IN_TIME_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Time( IN_TIME_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Convert an Object to a Timestamp, without an Exception
    */
   public static java.sql.Timestamp getTimestamp( Object value )
   {
       try
       {
           return toTimestamp( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   /**
    * Convert an Object to a Timestamp.
    */
   public static java.sql.Timestamp toTimestamp( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Timestamp ) return (java.sql.Timestamp)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Timestamp( IN_TIMESTAMP_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Timestamp( IN_TIMESTAMP_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Tells you if the date part of a datetime is in a certain time range.
    */
   public static boolean isTimeInRange( java.sql.Time start, java.sql.Time end, java.util.Date d )
   {
       d=new java.sql.Time(d.getHours(),d.getMinutes(),d.getSeconds());
       
       if (start==null || end==null)
       {
           return false;
       }
       
       if (start.before(end)&&(!(d.after(start)&&d.before(end))))
       {
           return false;
       }
       
       if (end.before(start)&&(!(d.after(end)||d.before(start))))
       {
           return false;
       }   
       return true;
   }
   public static  int getYear( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.YEAR );
   }
   public static int getMonth( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MONTH );
   }
   public static int getDate( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.DATE );
   }
   public static int getHour( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.HOUR );
   }
   public static int getMinute( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MINUTE );
   }
   public static int getSeconds( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.SECOND );
   }
   public static int getMillisecond( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MILLISECOND );
   }
   
   /**
    * Convert an Object to a String using Dates
    */
   public static String toString( Object date )
   {
       if( date == null ) return null;
       
       if( java.sql.Timestamp.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_TIMESTAMP_FORMAT.format( date );
       }
       if( java.sql.Time.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_TIME_FORMAT.format( date );
       }
       if( java.sql.Date.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_DATE_FORMAT.format( date );
       }
       if( java.util.Date.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_DATETIME_FORMAT.format( date );
       }
       
       throw new IllegalArgumentException( "Unsupported type " + date.getClass() );
   }

}


 </source>
   
  
 
  



Roll the java.util.Date forward or backward

   <source lang="java">
  

/*

* Copyright Javelin Software, All rights reserved.
*/

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

* The DateUtil is used as a Utility Class for Dates.
* 
* @author Robin Sharp
*/

public class DateUtil {

   public final static long SECOND_MILLIS = 1000;
   public final static long MINUTE_MILLIS = SECOND_MILLIS*60;
   public final static long HOUR_MILLIS = MINUTE_MILLIS*60;
   public final static long DAY_MILLIS = HOUR_MILLIS*24;
   public final static long YEAR_MILLIS = DAY_MILLIS*365;
   public static DateFormat OUT_DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy");
   public static DateFormat OUT_TIME_FORMAT = new SimpleDateFormat("H:mm:ss");
   public static DateFormat OUT_DATETIME_FORMAT = new SimpleDateFormat("d/M/yyyy H:mm:ss");
   public static DateFormat OUT_TIMESTAMP_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss.SSS");
   
   public static DateFormat IN_DATE_FORMAT = new SimpleDateFormat("d/M/yy");
   public static DateFormat IN_TIME_FORMAT = new SimpleDateFormat("H:mm:ss");
   public static DateFormat IN_DATETIME_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss");
   public static DateFormat IN_TIMESTAMP_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss.SSS");
   
   public static DateFormat DATE_TIME_FORMAT= new SimpleDateFormat( "yyyyMMddkkmmss" );  
   public static Calendar calendar = new GregorianCalendar();
   static
   {
       IN_DATE_FORMAT.setLenient(false);
       IN_TIME_FORMAT.setLenient(false);
       IN_DATETIME_FORMAT.setLenient(false);
   }
   /**
    * Create a new DateTime. To the last second. This will not create any 
    * extra-millis-seconds, which may cause bugs when writing to stores such as
    * databases that round milli-seconds up and down. 
    */
   public static java.util.Date newDateTime()
   {
       return new java.util.Date( (System.currentTimeMillis()/SECOND_MILLIS)*SECOND_MILLIS);
   }
   /**
    * Create a new Date. To the last day.
    */
   public static java.sql.Date newDate()
   {
       return new java.sql.Date( (System.currentTimeMillis()/DAY_MILLIS)*DAY_MILLIS);
   }
   
   /**
    * Create a new Time, with no date component. 
    */
   public static java.sql.Time newTime()
   {
       return new java.sql.Time( System.currentTimeMillis()%DAY_MILLIS);
   }
   
   /**
    * Create a new Timestamp. 
    */
   public static java.sql.Timestamp newTimestamp()
   {
       return new java.sql.Timestamp( System.currentTimeMillis() );
   }
   
   /**
    * Get the seconds difference
    */
   public static int secondsDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/SECOND_MILLIS) - (earlierDate.getTime()/SECOND_MILLIS));
   }
   /**
    * Get the minutes difference
    */
   public static int minutesDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/MINUTE_MILLIS) - (earlierDate.getTime()/MINUTE_MILLIS));
   }
   
   /**
    * Get the hours difference
    */
   public static int hoursDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/HOUR_MILLIS) - (earlierDate.getTime()/HOUR_MILLIS));
   }
   
   /**
    * Get the days difference
    */
   public static int daysDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/DAY_MILLIS) - (earlierDate.getTime()/DAY_MILLIS));
   }
   
  /**
   * Roll the java.util.Time forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.sql.Time rollTime( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.sql.Time(gc.getTime().getTime());
   }
   
  /**
   * Roll the java.util.Date forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.util.Date rollDateTime( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.util.Date(gc.getTime().getTime());
   }
   
  /**
   * Roll the java.sql.Date forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.sql.Date rollDate( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.sql.Date(gc.getTime().getTime());
   }
   
  /**
   * Roll the years forward or backward.
   * @param startDate - The start date
   * @param years - Negative to rollbackwards.
   */
   public static java.sql.Date rollYears( java.util.Date startDate, int years )
   {
       return rollDate( startDate, Calendar.YEAR, years );
   }
  /**
   * Roll the days forward or backward.
   * @param startDate - The start date
   * @param months - Negative to rollbackwards.
   */
   public static java.sql.Date rollMonths( java.util.Date startDate, int months )
   {
       return rollDate( startDate, Calendar.MONTH, months );
   }
  /**
   * Roll the days forward or backward.
   * @param startDate - The start date
   * @param days - Negative to rollbackwards.
   */
   public static java.sql.Date rollDays( java.util.Date startDate, int days )
   {
       return rollDate( startDate, Calendar.DATE, days );
   }
   
    /**
     * Checks the day, month and year are equal.
     */
    public static boolean dateEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;
       
       return d1.getDate() == d2.getDate() &&
              d1.getMonth() == d2.getMonth() &&
              d1.getYear() == d2.getYear();
    }
    
    /**
     * Checks the hour, minute and second are equal.
     */
    public static boolean timeEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;
       
       return d1.getHours() == d2.getHours() &&
              d1.getMinutes() == d2.getMinutes() &&
              d1.getSeconds() == d2.getSeconds();
    }
   /**
     * Checks the second, hour, month, day, month and year are equal.
     */
    public static boolean dateTimeEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;               
       
       return d1.getDate() == d2.getDate() &&
              d1.getMonth() == d2.getMonth() &&
              d1.getYear() == d2.getYear() &&
              d1.getHours() == d2.getHours() &&
              d1.getMinutes() == d2.getMinutes() &&
              d1.getSeconds() == d2.getSeconds();
    }
    
    /**
    * Convert an Object of type Classs to an Object.
    */
   public static Object toObject( Class clazz, Object value ) throws ParseException
   {
       if( value == null ) return null;
       if( clazz == null ) return value;
       
       if( java.sql.Date.class.isAssignableFrom( clazz ) ) return toDate( value );
       if( java.sql.Time.class.isAssignableFrom( clazz ) ) return toTime( value );
       if( java.sql.Timestamp.class.isAssignableFrom( clazz ) ) return toTimestamp( value );
       if( java.util.Date.class.isAssignableFrom( clazz ) ) return toDateTime( value );
       
       return value;
   }
   
   /**
    * Convert an Object to a DateTime, without an Exception
    */
   public static java.util.Date getDateTime( Object value )
   {
       try
       {
           return toDateTime( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   
   /**
    * Convert an Object to a DateTime.
    */
   public static java.util.Date toDateTime( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.util.Date ) return (java.util.Date)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return IN_DATETIME_FORMAT.parse( (String)value );
       }
               
       return IN_DATETIME_FORMAT.parse( value.toString() );
   }
   
   /**
    * Convert an Object to a Date, without an Exception
    */
   public static java.sql.Date getDate( Object value )
   {
       try
       {
           return toDate( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   /**
    * Convert an Object to a Date.
    */
   public static java.sql.Date toDate( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Date ) return (java.sql.Date)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Date( IN_DATE_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Date( IN_DATE_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Convert an Object to a Time, without an Exception
    */
   public static java.sql.Time getTime( Object value )
   {
       try
       {
           return toTime( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   
   /**
    * Convert an Object to a Time.
    */
   public static java.sql.Time toTime( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Time ) return (java.sql.Time)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Time( IN_TIME_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Time( IN_TIME_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Convert an Object to a Timestamp, without an Exception
    */
   public static java.sql.Timestamp getTimestamp( Object value )
   {
       try
       {
           return toTimestamp( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   /**
    * Convert an Object to a Timestamp.
    */
   public static java.sql.Timestamp toTimestamp( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Timestamp ) return (java.sql.Timestamp)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Timestamp( IN_TIMESTAMP_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Timestamp( IN_TIMESTAMP_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Tells you if the date part of a datetime is in a certain time range.
    */
   public static boolean isTimeInRange( java.sql.Time start, java.sql.Time end, java.util.Date d )
   {
       d=new java.sql.Time(d.getHours(),d.getMinutes(),d.getSeconds());
       
       if (start==null || end==null)
       {
           return false;
       }
       
       if (start.before(end)&&(!(d.after(start)&&d.before(end))))
       {
           return false;
       }
       
       if (end.before(start)&&(!(d.after(end)||d.before(start))))
       {
           return false;
       }   
       return true;
   }
   public static  int getYear( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.YEAR );
   }
   public static int getMonth( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MONTH );
   }
   public static int getDate( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.DATE );
   }
   public static int getHour( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.HOUR );
   }
   public static int getMinute( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MINUTE );
   }
   public static int getSeconds( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.SECOND );
   }
   public static int getMillisecond( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MILLISECOND );
   }
   
   /**
    * Convert an Object to a String using Dates
    */
   public static String toString( Object date )
   {
       if( date == null ) return null;
       
       if( java.sql.Timestamp.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_TIMESTAMP_FORMAT.format( date );
       }
       if( java.sql.Time.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_TIME_FORMAT.format( date );
       }
       if( java.sql.Date.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_DATE_FORMAT.format( date );
       }
       if( java.util.Date.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_DATETIME_FORMAT.format( date );
       }
       
       throw new IllegalArgumentException( "Unsupported type " + date.getClass() );
   }

}


 </source>
   
  
 
  



Roll the java.util.Time forward or backward

   <source lang="java">
  

/*

* Copyright Javelin Software, All rights reserved.
*/

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

* The DateUtil is used as a Utility Class for Dates.
* 
* @author Robin Sharp
*/

public class DateUtil {

   public final static long SECOND_MILLIS = 1000;
   public final static long MINUTE_MILLIS = SECOND_MILLIS*60;
   public final static long HOUR_MILLIS = MINUTE_MILLIS*60;
   public final static long DAY_MILLIS = HOUR_MILLIS*24;
   public final static long YEAR_MILLIS = DAY_MILLIS*365;
   public static DateFormat OUT_DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy");
   public static DateFormat OUT_TIME_FORMAT = new SimpleDateFormat("H:mm:ss");
   public static DateFormat OUT_DATETIME_FORMAT = new SimpleDateFormat("d/M/yyyy H:mm:ss");
   public static DateFormat OUT_TIMESTAMP_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss.SSS");
   
   public static DateFormat IN_DATE_FORMAT = new SimpleDateFormat("d/M/yy");
   public static DateFormat IN_TIME_FORMAT = new SimpleDateFormat("H:mm:ss");
   public static DateFormat IN_DATETIME_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss");
   public static DateFormat IN_TIMESTAMP_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss.SSS");
   
   public static DateFormat DATE_TIME_FORMAT= new SimpleDateFormat( "yyyyMMddkkmmss" );  
   public static Calendar calendar = new GregorianCalendar();
   static
   {
       IN_DATE_FORMAT.setLenient(false);
       IN_TIME_FORMAT.setLenient(false);
       IN_DATETIME_FORMAT.setLenient(false);
   }
   /**
    * Create a new DateTime. To the last second. This will not create any 
    * extra-millis-seconds, which may cause bugs when writing to stores such as
    * databases that round milli-seconds up and down. 
    */
   public static java.util.Date newDateTime()
   {
       return new java.util.Date( (System.currentTimeMillis()/SECOND_MILLIS)*SECOND_MILLIS);
   }
   /**
    * Create a new Date. To the last day.
    */
   public static java.sql.Date newDate()
   {
       return new java.sql.Date( (System.currentTimeMillis()/DAY_MILLIS)*DAY_MILLIS);
   }
   
   /**
    * Create a new Time, with no date component. 
    */
   public static java.sql.Time newTime()
   {
       return new java.sql.Time( System.currentTimeMillis()%DAY_MILLIS);
   }
   
   /**
    * Create a new Timestamp. 
    */
   public static java.sql.Timestamp newTimestamp()
   {
       return new java.sql.Timestamp( System.currentTimeMillis() );
   }
   
   /**
    * Get the seconds difference
    */
   public static int secondsDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/SECOND_MILLIS) - (earlierDate.getTime()/SECOND_MILLIS));
   }
   /**
    * Get the minutes difference
    */
   public static int minutesDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/MINUTE_MILLIS) - (earlierDate.getTime()/MINUTE_MILLIS));
   }
   
   /**
    * Get the hours difference
    */
   public static int hoursDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/HOUR_MILLIS) - (earlierDate.getTime()/HOUR_MILLIS));
   }
   
   /**
    * Get the days difference
    */
   public static int daysDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/DAY_MILLIS) - (earlierDate.getTime()/DAY_MILLIS));
   }
   
  /**
   * Roll the java.util.Time forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.sql.Time rollTime( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.sql.Time(gc.getTime().getTime());
   }
   
  /**
   * Roll the java.util.Date forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.util.Date rollDateTime( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.util.Date(gc.getTime().getTime());
   }
   
  /**
   * Roll the java.sql.Date forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.sql.Date rollDate( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.sql.Date(gc.getTime().getTime());
   }
   
  /**
   * Roll the years forward or backward.
   * @param startDate - The start date
   * @param years - Negative to rollbackwards.
   */
   public static java.sql.Date rollYears( java.util.Date startDate, int years )
   {
       return rollDate( startDate, Calendar.YEAR, years );
   }
  /**
   * Roll the days forward or backward.
   * @param startDate - The start date
   * @param months - Negative to rollbackwards.
   */
   public static java.sql.Date rollMonths( java.util.Date startDate, int months )
   {
       return rollDate( startDate, Calendar.MONTH, months );
   }
  /**
   * Roll the days forward or backward.
   * @param startDate - The start date
   * @param days - Negative to rollbackwards.
   */
   public static java.sql.Date rollDays( java.util.Date startDate, int days )
   {
       return rollDate( startDate, Calendar.DATE, days );
   }
   
    /**
     * Checks the day, month and year are equal.
     */
    public static boolean dateEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;
       
       return d1.getDate() == d2.getDate() &&
              d1.getMonth() == d2.getMonth() &&
              d1.getYear() == d2.getYear();
    }
    
    /**
     * Checks the hour, minute and second are equal.
     */
    public static boolean timeEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;
       
       return d1.getHours() == d2.getHours() &&
              d1.getMinutes() == d2.getMinutes() &&
              d1.getSeconds() == d2.getSeconds();
    }
   /**
     * Checks the second, hour, month, day, month and year are equal.
     */
    public static boolean dateTimeEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;               
       
       return d1.getDate() == d2.getDate() &&
              d1.getMonth() == d2.getMonth() &&
              d1.getYear() == d2.getYear() &&
              d1.getHours() == d2.getHours() &&
              d1.getMinutes() == d2.getMinutes() &&
              d1.getSeconds() == d2.getSeconds();
    }
    
    /**
    * Convert an Object of type Classs to an Object.
    */
   public static Object toObject( Class clazz, Object value ) throws ParseException
   {
       if( value == null ) return null;
       if( clazz == null ) return value;
       
       if( java.sql.Date.class.isAssignableFrom( clazz ) ) return toDate( value );
       if( java.sql.Time.class.isAssignableFrom( clazz ) ) return toTime( value );
       if( java.sql.Timestamp.class.isAssignableFrom( clazz ) ) return toTimestamp( value );
       if( java.util.Date.class.isAssignableFrom( clazz ) ) return toDateTime( value );
       
       return value;
   }
   
   /**
    * Convert an Object to a DateTime, without an Exception
    */
   public static java.util.Date getDateTime( Object value )
   {
       try
       {
           return toDateTime( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   
   /**
    * Convert an Object to a DateTime.
    */
   public static java.util.Date toDateTime( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.util.Date ) return (java.util.Date)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return IN_DATETIME_FORMAT.parse( (String)value );
       }
               
       return IN_DATETIME_FORMAT.parse( value.toString() );
   }
   
   /**
    * Convert an Object to a Date, without an Exception
    */
   public static java.sql.Date getDate( Object value )
   {
       try
       {
           return toDate( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   /**
    * Convert an Object to a Date.
    */
   public static java.sql.Date toDate( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Date ) return (java.sql.Date)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Date( IN_DATE_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Date( IN_DATE_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Convert an Object to a Time, without an Exception
    */
   public static java.sql.Time getTime( Object value )
   {
       try
       {
           return toTime( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   
   /**
    * Convert an Object to a Time.
    */
   public static java.sql.Time toTime( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Time ) return (java.sql.Time)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Time( IN_TIME_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Time( IN_TIME_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Convert an Object to a Timestamp, without an Exception
    */
   public static java.sql.Timestamp getTimestamp( Object value )
   {
       try
       {
           return toTimestamp( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   /**
    * Convert an Object to a Timestamp.
    */
   public static java.sql.Timestamp toTimestamp( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Timestamp ) return (java.sql.Timestamp)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Timestamp( IN_TIMESTAMP_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Timestamp( IN_TIMESTAMP_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Tells you if the date part of a datetime is in a certain time range.
    */
   public static boolean isTimeInRange( java.sql.Time start, java.sql.Time end, java.util.Date d )
   {
       d=new java.sql.Time(d.getHours(),d.getMinutes(),d.getSeconds());
       
       if (start==null || end==null)
       {
           return false;
       }
       
       if (start.before(end)&&(!(d.after(start)&&d.before(end))))
       {
           return false;
       }
       
       if (end.before(start)&&(!(d.after(end)||d.before(start))))
       {
           return false;
       }   
       return true;
   }
   public static  int getYear( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.YEAR );
   }
   public static int getMonth( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MONTH );
   }
   public static int getDate( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.DATE );
   }
   public static int getHour( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.HOUR );
   }
   public static int getMinute( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MINUTE );
   }
   public static int getSeconds( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.SECOND );
   }
   public static int getMillisecond( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MILLISECOND );
   }
   
   /**
    * Convert an Object to a String using Dates
    */
   public static String toString( Object date )
   {
       if( date == null ) return null;
       
       if( java.sql.Timestamp.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_TIMESTAMP_FORMAT.format( date );
       }
       if( java.sql.Time.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_TIME_FORMAT.format( date );
       }
       if( java.sql.Date.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_DATE_FORMAT.format( date );
       }
       if( java.util.Date.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_DATETIME_FORMAT.format( date );
       }
       
       throw new IllegalArgumentException( "Unsupported type " + date.getClass() );
   }

}


 </source>
   
  
 
  



Roll the years forward or backward

   <source lang="java">
  

/*

* Copyright Javelin Software, All rights reserved.
*/

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

* The DateUtil is used as a Utility Class for Dates.
* 
* @author Robin Sharp
*/

public class DateUtil {

   public final static long SECOND_MILLIS = 1000;
   public final static long MINUTE_MILLIS = SECOND_MILLIS*60;
   public final static long HOUR_MILLIS = MINUTE_MILLIS*60;
   public final static long DAY_MILLIS = HOUR_MILLIS*24;
   public final static long YEAR_MILLIS = DAY_MILLIS*365;
   public static DateFormat OUT_DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy");
   public static DateFormat OUT_TIME_FORMAT = new SimpleDateFormat("H:mm:ss");
   public static DateFormat OUT_DATETIME_FORMAT = new SimpleDateFormat("d/M/yyyy H:mm:ss");
   public static DateFormat OUT_TIMESTAMP_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss.SSS");
   
   public static DateFormat IN_DATE_FORMAT = new SimpleDateFormat("d/M/yy");
   public static DateFormat IN_TIME_FORMAT = new SimpleDateFormat("H:mm:ss");
   public static DateFormat IN_DATETIME_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss");
   public static DateFormat IN_TIMESTAMP_FORMAT = new SimpleDateFormat("d/M/yy H:mm:ss.SSS");
   
   public static DateFormat DATE_TIME_FORMAT= new SimpleDateFormat( "yyyyMMddkkmmss" );  
   public static Calendar calendar = new GregorianCalendar();
   static
   {
       IN_DATE_FORMAT.setLenient(false);
       IN_TIME_FORMAT.setLenient(false);
       IN_DATETIME_FORMAT.setLenient(false);
   }
   /**
    * Create a new DateTime. To the last second. This will not create any 
    * extra-millis-seconds, which may cause bugs when writing to stores such as
    * databases that round milli-seconds up and down. 
    */
   public static java.util.Date newDateTime()
   {
       return new java.util.Date( (System.currentTimeMillis()/SECOND_MILLIS)*SECOND_MILLIS);
   }
   /**
    * Create a new Date. To the last day.
    */
   public static java.sql.Date newDate()
   {
       return new java.sql.Date( (System.currentTimeMillis()/DAY_MILLIS)*DAY_MILLIS);
   }
   
   /**
    * Create a new Time, with no date component. 
    */
   public static java.sql.Time newTime()
   {
       return new java.sql.Time( System.currentTimeMillis()%DAY_MILLIS);
   }
   
   /**
    * Create a new Timestamp. 
    */
   public static java.sql.Timestamp newTimestamp()
   {
       return new java.sql.Timestamp( System.currentTimeMillis() );
   }
   
   /**
    * Get the seconds difference
    */
   public static int secondsDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/SECOND_MILLIS) - (earlierDate.getTime()/SECOND_MILLIS));
   }
   /**
    * Get the minutes difference
    */
   public static int minutesDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/MINUTE_MILLIS) - (earlierDate.getTime()/MINUTE_MILLIS));
   }
   
   /**
    * Get the hours difference
    */
   public static int hoursDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/HOUR_MILLIS) - (earlierDate.getTime()/HOUR_MILLIS));
   }
   
   /**
    * Get the days difference
    */
   public static int daysDiff( Date earlierDate, Date laterDate )
   {
       if( earlierDate == null || laterDate == null ) return 0;
       
       return (int)((laterDate.getTime()/DAY_MILLIS) - (earlierDate.getTime()/DAY_MILLIS));
   }
   
  /**
   * Roll the java.util.Time forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.sql.Time rollTime( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.sql.Time(gc.getTime().getTime());
   }
   
  /**
   * Roll the java.util.Date forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.util.Date rollDateTime( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.util.Date(gc.getTime().getTime());
   }
   
  /**
   * Roll the java.sql.Date forward or backward.
   * @param startDate - The start date
   * @period Calendar.YEAR etc
   * @param amount - Negative to rollbackwards.
   */
   public static java.sql.Date rollDate( java.util.Date startDate, int period, int amount )
   {
       GregorianCalendar gc = new GregorianCalendar();
       gc.setTime(startDate);
       gc.add(period, amount);
       return new java.sql.Date(gc.getTime().getTime());
   }
   
  /**
   * Roll the years forward or backward.
   * @param startDate - The start date
   * @param years - Negative to rollbackwards.
   */
   public static java.sql.Date rollYears( java.util.Date startDate, int years )
   {
       return rollDate( startDate, Calendar.YEAR, years );
   }
  /**
   * Roll the days forward or backward.
   * @param startDate - The start date
   * @param months - Negative to rollbackwards.
   */
   public static java.sql.Date rollMonths( java.util.Date startDate, int months )
   {
       return rollDate( startDate, Calendar.MONTH, months );
   }
  /**
   * Roll the days forward or backward.
   * @param startDate - The start date
   * @param days - Negative to rollbackwards.
   */
   public static java.sql.Date rollDays( java.util.Date startDate, int days )
   {
       return rollDate( startDate, Calendar.DATE, days );
   }
   
    /**
     * Checks the day, month and year are equal.
     */
    public static boolean dateEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;
       
       return d1.getDate() == d2.getDate() &&
              d1.getMonth() == d2.getMonth() &&
              d1.getYear() == d2.getYear();
    }
    
    /**
     * Checks the hour, minute and second are equal.
     */
    public static boolean timeEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;
       
       return d1.getHours() == d2.getHours() &&
              d1.getMinutes() == d2.getMinutes() &&
              d1.getSeconds() == d2.getSeconds();
    }
   /**
     * Checks the second, hour, month, day, month and year are equal.
     */
    public static boolean dateTimeEquals( java.util.Date d1, java.util.Date d2 )
    {
       if( d1 == null || d2 == null ) return false;               
       
       return d1.getDate() == d2.getDate() &&
              d1.getMonth() == d2.getMonth() &&
              d1.getYear() == d2.getYear() &&
              d1.getHours() == d2.getHours() &&
              d1.getMinutes() == d2.getMinutes() &&
              d1.getSeconds() == d2.getSeconds();
    }
    
    /**
    * Convert an Object of type Classs to an Object.
    */
   public static Object toObject( Class clazz, Object value ) throws ParseException
   {
       if( value == null ) return null;
       if( clazz == null ) return value;
       
       if( java.sql.Date.class.isAssignableFrom( clazz ) ) return toDate( value );
       if( java.sql.Time.class.isAssignableFrom( clazz ) ) return toTime( value );
       if( java.sql.Timestamp.class.isAssignableFrom( clazz ) ) return toTimestamp( value );
       if( java.util.Date.class.isAssignableFrom( clazz ) ) return toDateTime( value );
       
       return value;
   }
   
   /**
    * Convert an Object to a DateTime, without an Exception
    */
   public static java.util.Date getDateTime( Object value )
   {
       try
       {
           return toDateTime( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   
   /**
    * Convert an Object to a DateTime.
    */
   public static java.util.Date toDateTime( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.util.Date ) return (java.util.Date)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return IN_DATETIME_FORMAT.parse( (String)value );
       }
               
       return IN_DATETIME_FORMAT.parse( value.toString() );
   }
   
   /**
    * Convert an Object to a Date, without an Exception
    */
   public static java.sql.Date getDate( Object value )
   {
       try
       {
           return toDate( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   /**
    * Convert an Object to a Date.
    */
   public static java.sql.Date toDate( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Date ) return (java.sql.Date)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Date( IN_DATE_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Date( IN_DATE_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Convert an Object to a Time, without an Exception
    */
   public static java.sql.Time getTime( Object value )
   {
       try
       {
           return toTime( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   
   /**
    * Convert an Object to a Time.
    */
   public static java.sql.Time toTime( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Time ) return (java.sql.Time)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Time( IN_TIME_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Time( IN_TIME_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Convert an Object to a Timestamp, without an Exception
    */
   public static java.sql.Timestamp getTimestamp( Object value )
   {
       try
       {
           return toTimestamp( value );
       }
       catch( ParseException pe )
       {
           pe.printStackTrace();
           return null;
       }
   }
   /**
    * Convert an Object to a Timestamp.
    */
   public static java.sql.Timestamp toTimestamp( Object value ) throws ParseException
   {
       if( value == null ) return null;        
       if( value instanceof java.sql.Timestamp ) return (java.sql.Timestamp)value;
       if( value instanceof String )
       {
           if( "".equals( (String)value ) ) return null;
           return new java.sql.Timestamp( IN_TIMESTAMP_FORMAT.parse( (String)value ).getTime() );
       }
               
       return new java.sql.Timestamp( IN_TIMESTAMP_FORMAT.parse( value.toString() ).getTime() );
   }
   
   /**
    * Tells you if the date part of a datetime is in a certain time range.
    */
   public static boolean isTimeInRange( java.sql.Time start, java.sql.Time end, java.util.Date d )
   {
       d=new java.sql.Time(d.getHours(),d.getMinutes(),d.getSeconds());
       
       if (start==null || end==null)
       {
           return false;
       }
       
       if (start.before(end)&&(!(d.after(start)&&d.before(end))))
       {
           return false;
       }
       
       if (end.before(start)&&(!(d.after(end)||d.before(start))))
       {
           return false;
       }   
       return true;
   }
   public static  int getYear( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.YEAR );
   }
   public static int getMonth( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MONTH );
   }
   public static int getDate( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.DATE );
   }
   public static int getHour( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.HOUR );
   }
   public static int getMinute( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MINUTE );
   }
   public static int getSeconds( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.SECOND );
   }
   public static int getMillisecond( Date date )
   {
       calendar.setTime( date );
       return calendar.get( Calendar.MILLISECOND );
   }
   
   /**
    * Convert an Object to a String using Dates
    */
   public static String toString( Object date )
   {
       if( date == null ) return null;
       
       if( java.sql.Timestamp.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_TIMESTAMP_FORMAT.format( date );
       }
       if( java.sql.Time.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_TIME_FORMAT.format( date );
       }
       if( java.sql.Date.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_DATE_FORMAT.format( date );
       }
       if( java.util.Date.class.isAssignableFrom( date.getClass() ) )
       {
           return OUT_DATETIME_FORMAT.format( date );
       }
       
       throw new IllegalArgumentException( "Unsupported type " + date.getClass() );
   }

}


 </source>
   
  
 
  



Round this date, leaving the field specified as the most significant field.

   <source lang="java">
 

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 {

 private static final int[][] fields = {
   {Calendar.MILLISECOND},
   {Calendar.SECOND},
   {Calendar.MINUTE},
   {Calendar.HOUR_OF_DAY, Calendar.HOUR},
   {Calendar.DATE, Calendar.DAY_OF_MONTH, Calendar.AM_PM 
       /* Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK, Calendar.DAY_OF_WEEK_IN_MONTH */
   },
   {Calendar.MONTH, DateUtils.SEMI_MONTH},
   {Calendar.YEAR},
   {Calendar.ERA}};
 /**
*

Round this date, leaving the field specified as the most * significant field.

  *
*

For example, if you had the datetime of 28 Mar 2002 * 13:45:01.231, if this was passed with HOUR, it would return * 28 Mar 2002 14:00:00.000. If this was passed with MONTH, it * would return 1 April 2002 0:00:00.000.

  * 
*

For a date in a timezone that handles the change to daylight * saving time, rounding to Calendar.HOUR_OF_DAY will behave as follows. * Suppose daylight saving time begins at 02:00 on March 30. Rounding a * date that crosses this time would produce the following values: *

    *
  • March 30, 2003 01:10 rounds to March 30, 2003 01:00
  • *
  • March 30, 2003 01:40 rounds to March 30, 2003 03:00
  • *
  • March 30, 2003 02:10 rounds to March 30, 2003 03:00
  • *
  • March 30, 2003 02:40 rounds to March 30, 2003 04:00
  • *
*

  * 
  * @param date  the date to work with
  * @param field  the field from Calendar
  *  or SEMI_MONTH
  * @return the rounded date (a different object)
  * @throws IllegalArgumentException if the date is null
  * @throws ArithmeticException if the year is over 280 million
  */
 public static Calendar round(Calendar date, int field) {
     if (date == null) {
         throw new IllegalArgumentException("The date must not be null");
     }
     Calendar rounded = (Calendar) date.clone();
     modify(rounded, field, true);
     return rounded;
 }
 //-----------------------------------------------------------------------
 /**
*

Internal calculation method.

  * 
  * @param val  the calendar
  * @param field  the field constant
  * @param round  true to round, false to truncate
  * @throws ArithmeticException if the year is over 280 million
  */
 private static void modify(Calendar val, int field, boolean round) {
     if (val.get(Calendar.YEAR) > 280000000) {
         throw new ArithmeticException("Calendar value too large for accurate calculations");
     }
     
     if (field == Calendar.MILLISECOND) {
         return;
     }
     // ----------------- Fix for LANG-59 ---------------------- START ---------------
     // see http://issues.apache.org/jira/browse/LANG-59
     //
     // Manually truncate milliseconds, seconds and minutes, rather than using
     // Calendar methods.
     Date date = val.getTime();
     long time = date.getTime();
     boolean done = false;
     // truncate milliseconds
     int millisecs = val.get(Calendar.MILLISECOND);
     if (!round || millisecs < 500) {
         time = time - millisecs;
     }
     if (field == Calendar.SECOND) {
         done = true;
     }
     // truncate seconds
     int seconds = val.get(Calendar.SECOND);
     if (!done && (!round || seconds < 30)) {
         time = time - (seconds * 1000L);
     }
     if (field == Calendar.MINUTE) {
         done = true;
     }
     // truncate minutes
     int minutes = val.get(Calendar.MINUTE);
     if (!done && (!round || minutes < 30)) {
         time = time - (minutes * 60000L);
     }
     // reset time
     if (date.getTime() != time) {
         date.setTime(time);
         val.setTime(date);
     }
     // ----------------- Fix for LANG-59 ----------------------- END ----------------
     boolean roundUp = false;
     for (int i = 0; i < fields.length; i++) {
         for (int j = 0; j < fields[i].length; j++) {
             if (fields[i][j] == field) {
                 //This is our field... we stop looping
                 if (round && roundUp) {
                     if (field == DateUtils.SEMI_MONTH) {
                         //This is a special case that"s hard to generalize
                         //If the date is 1, we round up to 16, otherwise
                         //  we subtract 15 days and add 1 month
                         if (val.get(Calendar.DATE) == 1) {
                             val.add(Calendar.DATE, 15);
                         } else {
                             val.add(Calendar.DATE, -15);
                             val.add(Calendar.MONTH, 1);
                         }
                     } else {
                         //We need at add one to this field since the
                         //  last number causes us to round up
                         val.add(fields[i][0], 1);
                     }
                 }
                 return;
             }
         }
         //We have various fields that are not easy roundings
         int offset = 0;
         boolean offsetSet = false;
         //These are special types of fields that require different rounding rules
         switch (field) {
             case DateUtils.SEMI_MONTH:
                 if (fields[i][0] == Calendar.DATE) {
                     //If we"re going to drop the DATE field"s value,
                     //  we want to do this our own way.
                     //We need to subtrace 1 since the date has a minimum of 1
                     offset = val.get(Calendar.DATE) - 1;
                     //If we"re above 15 days adjustment, that means we"re in the
                     //  bottom half of the month and should stay accordingly.
                     if (offset >= 15) {
                         offset -= 15;
                     }
                     //Record whether we"re in the top or bottom half of that range
                     roundUp = offset > 7;
                     offsetSet = true;
                 }
                 break;
             case Calendar.AM_PM:
                 if (fields[i][0] == Calendar.HOUR_OF_DAY) {
                     //If we"re going to drop the HOUR field"s value,
                     //  we want to do this our own way.
                     offset = val.get(Calendar.HOUR_OF_DAY);
                     if (offset >= 12) {
                         offset -= 12;
                     }
                     roundUp = offset > 6;
                     offsetSet = true;
                 }
                 break;
         }
         if (!offsetSet) {
             int min = val.getActualMinimum(fields[i][0]);
             int max = val.getActualMaximum(fields[i][0]);
             //Calculate the offset from the minimum allowed value
             offset = val.get(fields[i][0]) - min;
             //Set roundUp if this is more than half way between the minimum and maximum
             roundUp = offset > ((max - min) / 2);
         }
         //We need to remove this field
         if (offset != 0) {
             val.set(fields[i][0], val.get(fields[i][0]) - offset);
         }
     }
     throw new IllegalArgumentException("The field " + field + " is not supported");
 }

}


 </source>
   
  
 
  



Utilities to working with dates java.util.Date

   <source lang="java">
 

import java.text.DateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale;


/**

* Utilities to working with dates (java.util.Date).

* * @author Javier Paniza * @author Peter Smith */ public class Dates { /** * With hour to 0. * If day, month and year are 0 return null. */ public static Date create(int day, int month, int year) { return create(day, month, year, 0, 0, 0); } /** * If day, month and year are 0 return null. */ public static Date create(int day, int month, int year, int hourofday, int minute, int second) { if (day == 0 && month == 0 && year == 0) return null; Calendar cal = Calendar.getInstance(); cal.set(year, month - 1, day, hourofday, minute, second); cal.set(Calendar.MILLISECOND, 0); return cal.getTime(); } /** * Current date without time. */ public static Date createCurrent() { return removeTime(new java.util.Date()); } /** * Returns the day of date. <p> * * If date is null return 0. */ public static int getDay(Date date) { if (date == null) return 0; Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal.get(Calendar.DAY_OF_MONTH); } /** * Returns the year (4 digits) of date. <o> * * If date is null returns 0. */ public static int getYear(Date date) { if (date == null) return 0; Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal.get(Calendar.YEAR); } /** * Returns the month (1 to 12) of date. <p> * * If date is null returns 0. */ public static int getMonth(Date date) { if (date == null) return 0; Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal.get(Calendar.MONTH) + 1; } /** * Put the day to the date. <p> * * If date is null it has no effect (but no exception is thrown) */ public static void setDay(Date date, int day) { if (date == null) return; Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.set(Calendar.DAY_OF_MONTH, day); } /** * Put the month (1 to 12) to the date. <p> * * If date is null it has no effect (but no exception is thrown) */ public static void setMonth(Date date, int month) { if (date == null) return; Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.set(Calendar.MONTH, month - 1); } /** * Put the year to the date. <p> * * If date is null it has no effect (but no exception is thrown) */ public static void setYear(Date date, int year) { if (date == null) return; Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.set(Calendar.YEAR, year); } /** * Puts hours, minutes, seconds and milliseconds to zero. <p> * * @return The same date sent as argument (a new date is not created). If null * if sent a null is returned. */ public static Date removeTime(Date date) { if (date == null) return null; Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); date.setTime(cal.getTime().getTime()); return date; } /** * Returns a clone but without hours, minutes, seconds and milliseconds. <p> * * @return If null if sent a null is returned. */ public static Date cloneWithoutTime(Date date) { if (date == null) return null; Date result = (Date) date.clone(); removeTime(result); return result; } /** * Returns a clone but with 23:59:59:999 for hours, minutes, seconds and milliseconds. <p> * * @return The same date sent as argument (a new date is not created). If null * if sent a null is returned. */ public static Date cloneWith2359(Date date) { if (date == null) return null; Date result = (Date) date.clone(); Calendar cal = Calendar.getInstance(); cal.setTime(result); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); cal.set(Calendar.MILLISECOND, 999); result.setTime(cal.getTime().getTime()); return result; } /** * Creates a java.sql.Date from a java.util.Date. <p> * * @param date If null returns null */ public static java.sql.Date toSQL(java.util.Date date) { if (date == null) return null; return new java.sql.Date(date.getTime()); } /** * Creates a date with day, month and year of original, * but with current time. <p> * * @param date It is not changed * @return If arguments is null then is null */ public static java.util.Date withTime(java.util.Date date) { if (date == null) return null; Calendar cal = Calendar.getInstance(); cal.setTime(date); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); cal.setTime(new java.util.Date()); cal.set(Calendar.YEAR, year); cal.set(Calendar.MONTH, month); cal.set(Calendar.DAY_OF_MONTH, day); return cal.getTime(); } /** * Compares if 2 dates are equals at day, month and year * level, ignoring time in comparing. * * @param f1 Can be null * @param f2 Can be null */ public static boolean isDifferentDay(java.util.Date f1, java.util.Date f2) { if (f1 == null && f2 == null) return false; if (f1 == null || f2 == null) return true; Calendar cal = Calendar.getInstance(); cal.setTime(f1); int dd1 = cal.get(Calendar.DAY_OF_MONTH); int mm1 = cal.get(Calendar.MONTH); int aa1 = cal.get(Calendar.YEAR); cal.setTime(f2); int dd2 = cal.get(Calendar.DAY_OF_MONTH); int mm2 = cal.get(Calendar.MONTH); int aa2 = cal.get(Calendar.YEAR); return !(aa1==aa2 && mm1==mm2 && dd1==dd2); } /** * Difference of 2 dates in years, months and days. <p> * * @param f1 If null returns null * @param f2 If null returns null */ public static DateDistance dateDistance(java.util.Date f1, java.util.Date f2, boolean includeStartDate ) { DateDistance df = new DateDistance(); if (null == f1 || null == f2) return null; Calendar fmax = Calendar.getInstance(), fmin = Calendar.getInstance(); f1 = Dates.removeTime(f1); f2 = Dates.removeTime(f2); if (f1.after(f2)) { fmax.setTime(f1); fmin.setTime(f2); } else { fmin.setTime(f1); fmax.setTime(f2); } int initDay = fmin.get(Calendar.DATE); int initMonth = fmin.get(Calendar.MONTH); int initYear = fmin.get(Calendar.YEAR); int endMonth = fmax.get(Calendar.MONTH); int endYear = fmax.get(Calendar.YEAR); int finalLimit = fmax.getActualMaximum(Calendar.DATE); int initPeak = 0; int finalPeak = 0; if (initMonth == endMonth && initYear == endYear) { while ( fmin.getTime().before(fmax.getTime()) ) { fmin.add(Calendar.DATE, 1); df.days++; } if (includeStartDate) { df.days++; } if (df.days >= finalLimit) { df.months++; df.days = 0; } return df; } if (initDay != 1) { while (fmin.get(Calendar.DATE) != 1) { fmin.add(Calendar.DATE, 1); initPeak++; } } while (fmin.get(Calendar.MONTH) != endMonth || fmin.get(Calendar.YEAR) != endYear) { fmin.add(Calendar.MONTH, 1); df.months++; if (df.months == 12) { df.years++; df.months = 0; } } while ( fmin.getTime().before(fmax.getTime()) ) { fmin.add(Calendar.DATE, 1); finalPeak++; } int peak = initPeak + finalPeak; if (includeStartDate) { peak++; } if (peak >= finalLimit) { peak = peak - finalLimit; df.months++; if (df.months == 12) { df.years++; df.months = 0; } } df.days = peak; return df; } /** * Difference of 2 dates in years, months and days. <p> * * @param f1 If null returns null * @param f2 If null returns null */ public static DateDistance dateDistance(java.util.Date f1, java.util.Date f2) { return dateDistance(f1, f2, false); } public static DateDistance addDateDistances(DateDistance dis1, DateDistance dis2) { DateDistance df=new DateDistance(); if ( null == dis1 || null == dis2 ) return null; int years, months, days; days = dis1.days + dis2.days; months = days / 30; days = days % 30; months = months + dis1.months + dis2.months ; years = months / 12 ; months = months % 12; years = years + ( dis1.years + dis2.years ); df.years = years; df.months=months; df.days=days; return df; } public static DateDistance subtractDateDistances(DateDistance dis1, DateDistance dis2) { DateDistance df = new DateDistance(); if ( null == dis1 || null == dis2 ) return null; int years=0; int months=0; int days=0; days = dis1.days - dis2.days; months = dis1.months - dis2.months; years =dis1.years - dis2.years; if (days<0) { days=days+30; months=months-1; } if (months<0){ months=months+12; years=years-1; } df.years = years; df.months = months; df.days = days; return df; } public static String dateFormatForJSCalendar(Locale locale) { DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale); String date = df.format(create(1, 2, 1971)); // d, m, y boolean always4InYear= "es".equals(locale.getLanguage()) || "pl".equals(locale.getLanguage()); String result = date. replaceAll("01", "%d"). replaceAll("02", "%m"). replaceAll("1971", "%Y"). replaceAll("71", always4InYear?"%Y":"%y"). replaceAll("1", "%d"). replaceAll("2", "%m"); return result; } public static String dateTimeFormatForJSCalendar(Locale locale) { DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale); String datetime = df.format(create(1, 2, 1971, 15, 59, 0)); // d, m, y, hr, min, sec boolean always4InYear= "es".equals(locale.getLanguage()) || "pl".equals(locale.getLanguage()); String result = datetime. // time part replaceAll("15", "%H"). // 24hr format replaceAll("03", "%I"). // 12hr format - double digit replaceAll("3", "%l"). // 12hr format - single digit replaceAll("59","%M"). // minute replaceAll("PM", "%p"). // AM/PM - uppercase replaceAll("pm", "%P"). // am/pm - lowercase // date part replaceAll("01", "%d"). // day - double digit replaceAll("02", "%m"). // month - double digit replaceAll("1971", "%Y"). // year - 4 digit replaceAll("71", always4InYear?"%Y":"%y"). // year - 2 digit replaceAll("1", "%e"). // day - single digit replaceAll("2", "%m") // month - ??? seems only double digit is supported by calendar  ; return result; } /** * Returns number of days between startDate and endDate<p> * * @param java.util.Date startDate * @param java.util.Date endDate * @param boolean includeStartDate<p> * */ public static int daysInterval (Date startDate, Date endDate, boolean includeStartDate ) { startDate = Dates.removeTime(startDate); Calendar start = Calendar.getInstance(); start.setTime(startDate); endDate = Dates.removeTime(endDate); Calendar end = Calendar.getInstance(); end.setTime(endDate); if (includeStartDate) { start.add(Calendar.DATE, -1); } int days = 0; while (start.before(end)) { days++; start.add(Calendar.DATE,1); } return days; } public static class DateDistance { public int days; public int months; public int years; } } </source>