Roll the years forward or backward : Date Calculation « Data Type « Java






Roll the years forward or backward

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

}

   
    
    
    
    
    
  








Related examples in the same category

1.Get the days difference
2.Get the days passed from the specified date up to the date provided in the constructor
3.Get the hours difference
4.Get the minutes difference
5.Get the seconds difference
6.Adds a number of days to a date returning a new object.
7.Adds a number of hours to a date returning a new object.
8.Adds a number of milliseconds to a date returning a new object.
9.Adds a number of minutes to a date returning a new object.
10.Adds a number of months to a date returning a new object.
11.Adds a number of seconds to a date returning a new object.
12.Adds a number of weeks to a date returning a new object.
13.Adds a number of years to a date returning a new object.
14.Returns a Date set just to Noon, to the closest possible millisecond of the day.
15.Returns a Date set to the first possible millisecond of the day, just after midnight.
16.Returns a Date set to the first possible millisecond of the month, just after midnight.
17.Returns a Date set to the last possible millisecond of the day, just before midnight.
18.Returns a Date set to the last possible millisecond of the minute.
19.Returns a Date set to the last possible millisecond of the month, just before midnight.
20.Returns a java.sql.Timestamp equal to the current time
21.Returns the number of days within the fragment.
22.Returns the number of hours within the fragment.
23.Returns the number of milliseconds within the fragment.
24.Returns the number of minutes within the fragment.
25.Returns the number of seconds within the fragment.
26.Returns true if endDate is after startDate or if startDate equals endDate.
27.Roll the days forward or backward
28.Roll the java.sql.Date forward or backward
29.Roll the java.util.Date forward or backward
30.Roll the java.util.Time forward or backward
31.Round this date, leaving the field specified as the most significant field.
32.Checking date as String formatted by a date format
33.Checks if a calendar date is after today and within a number of days in the future
34.Checks if a calendar date is today
35.Checks if a date is after today and within a number of days in the future
36.Checks if the first calendar date is after the second calendar date ignoring time
37.Checks if the first calendar date is before the second calendar date ignoring time
38.Checks if the first date is after the second date ignoring time
39.Checks if the first date is before the second date ignoring time
40.Checks if two calendars represent the same day ignoring time
41.Checks if two dates are on the same day ignoring time
42.Checks the day, month and year are equal
43.Checks the hour, minute and second are equal
44.Make the date go forward of the specified amount of minutes
45.Make the date go back of the specified amount of days
46.Returns the maximum of two dates. A null date is treated as being less than any non-null date
47.Utilities to working with dates java.util.Date
48.Calculate Holidays
49.Compare two dates
50.Convert time in milliseconds into a display string of the form [h]h:mm[am|pm]
51.convert a minute-of-week time to time of day as dd:dd [AM|PM]
52.Convert a minute-of-week time to time of day as dd:dd (24 hour format)
53.Convert passed time into an offset string
54.convert date in milliseconds into the native format of the server - i.e. minute of the week
55.Convert date in milliseconds into minute of the day
56.Convert date in minute of the week format into millisecond format
57.Convert milliseconds into the day of the week string
58.Convert milliseconds into a short day of the week string
59.Convert milliseconds into the month of the year string
60.Convert time to a sliding window format
61.Get age
62.Get Next Monday
63.Get next Sunday
64.Get File system Path From Date
65.Get today's date
66.Get Month, Day of Month, year from a Date
67.A method to get the last day of a month
68.Get Age
69.Get date of yesterday
70.Get date of last week
71.Get date of last month
72.Utility for setting the time on a date.
73.Get last Date of This Month
74.General purpose date utilities.
75.Get Last day from previous Month
76.Get Local Epoch