Get the hours difference : Date Calculation « Data Type « Java

Java
1. 2D Graphics GUI
2. 3D
3. Advanced Graphics
4. Ant
5. Apache Common
6. Chart
7. Class
8. Collections Data Structure
9. Data Type
10. Database SQL JDBC
11. Design Pattern
12. Development Class
13. EJB3
14. Email
15. Event
16. File Input Output
17. Game
18. Generics
19. GWT
20. Hibernate
21. I18N
22. J2EE
23. J2ME
24. JDK 6
25. JNDI LDAP
26. JPA
27. JSP
28. JSTL
29. Language Basics
30. Network Protocol
31. PDF RTF
32. Reflection
33. Regular Expressions
34. Scripting
35. Security
36. Servlets
37. Spring
38. Swing Components
39. Swing JFC
40. SWT JFace Eclipse
41. Threads
42. Tiny Application
43. Velocity
44. Web Services SOA
45. XML
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java » Data Type » Date CalculationScreenshots 
Get the hours difference
   

/*
 * 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.TimeSystem.currentTimeMillis()%DAY_MILLIS);
    }
    
    /**
     * Create a new Timestamp. 
     */
    public static java.sql.Timestamp newTimestamp()
    {
        return new java.sql.TimestampSystem.currentTimeMillis() );
    }
    
    /**
     * Get the seconds difference
     */
    public static int secondsDiffDate earlierDate, Date laterDate )
    {
        ifearlierDate == null || laterDate == null return 0;
        
        return (int)((laterDate.getTime()/SECOND_MILLIS(earlierDate.getTime()/SECOND_MILLIS));
    }

    /**
     * Get the minutes difference
     */
    public static int minutesDiffDate earlierDate, Date laterDate )
    {
        ifearlierDate == null || laterDate == null return 0;
        
        return (int)((laterDate.getTime()/MINUTE_MILLIS(earlierDate.getTime()/MINUTE_MILLIS));
    }
    
    /**
     * Get the hours difference
     */
    public static int hoursDiffDate earlierDate, Date laterDate )
    {
        ifearlierDate == null || laterDate == null return 0;
        
        return (int)((laterDate.getTime()/HOUR_MILLIS(earlierDate.getTime()/HOUR_MILLIS));
    }
    
    /**
     * Get the days difference
     */
    public static int daysDiffDate earlierDate, Date laterDate )
    {
        ifearlierDate == 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 rollTimejava.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 rollDateTimejava.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 rollDatejava.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 rollYearsjava.util.Date startDate, int years )
    {
        return rollDatestartDate, Calendar.YEAR, years );
    }

   /**
    * Roll the days forward or backward.
    @param startDate - The start date
    @param months - Negative to rollbackwards.
    */
    public static java.sql.Date rollMonthsjava.util.Date startDate, int months )
    {
        return rollDatestartDate, Calendar.MONTH, months );
    }

   /**
    * Roll the days forward or backward.
    @param startDate - The start date
    @param days - Negative to rollbackwards.
    */
    public static java.sql.Date rollDaysjava.util.Date startDate, int days )
    {
        return rollDatestartDate, Calendar.DATE, days );
    }
    
     /**
      * Checks the day, month and year are equal.
      */
     public static boolean dateEqualsjava.util.Date d1, java.util.Date d2 )
     {
        ifd1 == 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 timeEqualsjava.util.Date d1, java.util.Date d2 )
     {
        ifd1 == 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 dateTimeEqualsjava.util.Date d1, java.util.Date d2 )
     {
        ifd1 == 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 toObjectClass clazz, Object value throws ParseException
    {
        ifvalue == null return null;
        ifclazz == null return value;
        
        ifjava.sql.Date.class.isAssignableFromclazz ) ) return toDatevalue );
        ifjava.sql.Time.class.isAssignableFromclazz ) ) return toTimevalue );
        ifjava.sql.Timestamp.class.isAssignableFromclazz ) ) return toTimestampvalue );
        ifjava.util.Date.class.isAssignableFromclazz ) ) return toDateTimevalue );
        
        return value;
    }
    
    /**
     * Convert an Object to a DateTime, without an Exception
     */
    public static java.util.Date getDateTimeObject value )
    {
        try
        {
            return toDateTimevalue );
        }
        catchParseException pe )
        {
            pe.printStackTrace();
            return null;
        }
    }
    
    /**
     * Convert an Object to a DateTime.
     */
    public static java.util.Date toDateTimeObject value throws ParseException
    {
        ifvalue == null return null;        
        ifvalue instanceof java.util.Date return (java.util.Date)value;
        ifvalue instanceof String )
        {
            if"".equals( (String)value ) ) return null;
            return IN_DATETIME_FORMAT.parse( (String)value );
        }
                
        return IN_DATETIME_FORMAT.parsevalue.toString() );
    }
    
    /**
     * Convert an Object to a Date, without an Exception
     */
    public static java.sql.Date getDateObject value )
    {
        try
        {
            return toDatevalue );
        }
        catchParseException pe )
        {
            pe.printStackTrace();
            return null;
        }
    }

    /**
     * Convert an Object to a Date.
     */
    public static java.sql.Date toDateObject value throws ParseException
    {
        ifvalue == null return null;        
        ifvalue instanceof java.sql.Date return (java.sql.Date)value;
        ifvalue instanceof String )
        {
            if"".equals( (String)value ) ) return null;
            return new java.sql.DateIN_DATE_FORMAT.parse( (String)value ).getTime() );
        }
                
        return new java.sql.DateIN_DATE_FORMAT.parsevalue.toString() ).getTime() );
    }
    
    /**
     * Convert an Object to a Time, without an Exception
     */
    public static java.sql.Time getTimeObject value )
    {
        try
        {
            return toTimevalue );
        }
        catchParseException pe )
        {
            pe.printStackTrace();
            return null;
        }
    }
    
    /**
     * Convert an Object to a Time.
     */
    public static java.sql.Time toTimeObject value throws ParseException
    {
        ifvalue == null return null;        
        ifvalue instanceof java.sql.Time return (java.sql.Time)value;
        ifvalue instanceof String )
        {
            if"".equals( (String)value ) ) return null;
            return new java.sql.TimeIN_TIME_FORMAT.parse( (String)value ).getTime() );
        }
                
        return new java.sql.TimeIN_TIME_FORMAT.parsevalue.toString() ).getTime() );
    }
    
    /**
     * Convert an Object to a Timestamp, without an Exception
     */
    public static java.sql.Timestamp getTimestampObject value )
    {
        try
        {
            return toTimestampvalue );
        }
        catchParseException pe )
        {
            pe.printStackTrace();
            return null;
        }
    }

    /**
     * Convert an Object to a Timestamp.
     */
    public static java.sql.Timestamp toTimestampObject value throws ParseException
    {
        ifvalue == null return null;        
        ifvalue instanceof java.sql.Timestamp return (java.sql.Timestamp)value;
        ifvalue instanceof String )
        {
            if"".equals( (String)value ) ) return null;
            return new java.sql.TimestampIN_TIMESTAMP_FORMAT.parse( (String)value ).getTime() );
        }
                
        return new java.sql.TimestampIN_TIMESTAMP_FORMAT.parsevalue.toString() ).getTime() );
    }
    
    /**
     * Tells you if the date part of a datetime is in a certain time range.
     */
    public static boolean isTimeInRangejava.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 getYearDate date )
    {
        calendar.setTimedate );
        return calendar.getCalendar.YEAR );
    }

    public static int getMonthDate date )
    {
        calendar.setTimedate );
        return calendar.getCalendar.MONTH );
    }

    public static int getDateDate date )
    {
        calendar.setTimedate );
        return calendar.getCalendar.DATE );
    }

    public static int getHourDate date )
    {
        calendar.setTimedate );
        return calendar.getCalendar.HOUR );
    }

    public static int getMinuteDate date )
    {
        calendar.setTimedate );
        return calendar.getCalendar.MINUTE );
    }

    public static int getSecondsDate date )
    {
        calendar.setTimedate );
        return calendar.getCalendar.SECOND );
    }

    public static int getMillisecondDate date )
    {
        calendar.setTimedate );
        return calendar.getCalendar.MILLISECOND );
    }
    
    /**
     * Convert an Object to a String using Dates
     */
    public static String toStringObject date )
    {
        ifdate == null return null;
        
        ifjava.sql.Timestamp.class.isAssignableFromdate.getClass() ) )
        {
            return OUT_TIMESTAMP_FORMAT.formatdate );
        }
        ifjava.sql.Time.class.isAssignableFromdate.getClass() ) )
        {
            return OUT_TIME_FORMAT.formatdate );
        }
        ifjava.sql.Date.class.isAssignableFromdate.getClass() ) )
        {
            return OUT_DATE_FORMAT.formatdate );
        }
        ifjava.util.Date.class.isAssignableFromdate.getClass() ) )
        {
            return OUT_DATETIME_FORMAT.formatdate );
        }
        
        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 minutes difference
4. Get the seconds difference
5. Adds a number of days to a date returning a new object.
6. Adds a number of hours to a date returning a new object.
7. Adds a number of milliseconds to a date returning a new object.
8. Adds a number of minutes to a date returning a new object.
9. Adds a number of months to a date returning a new object.
10. Adds a number of seconds to a date returning a new object.
11. Adds a number of weeks to a date returning a new object.
12. Adds a number of years to a date returning a new object.
13. Returns a Date set just to Noon, to the closest possible millisecond of the day.
14. Returns a Date set to the first possible millisecond of the day, just after midnight.
15. Returns a Date set to the first possible millisecond of the month, just after midnight.
16. Returns a Date set to the last possible millisecond of the day, just before midnight.
17. Returns a Date set to the last possible millisecond of the minute.
18. Returns a Date set to the last possible millisecond of the month, just before midnight.
19. Returns a java.sql.Timestamp equal to the current time
20. Returns the number of days within the fragment.
21. Returns the number of hours within the fragment.
22. Returns the number of milliseconds within the fragment.
23. Returns the number of minutes within the fragment.
24. Returns the number of seconds within the fragment.
25. Returns true if endDate is after startDate or if startDate equals endDate.
26. Roll the days forward or backward
27. Roll the java.sql.Date forward or backward
28. Roll the java.util.Date forward or backward
29. Roll the java.util.Time forward or backward
30. Roll the years 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
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.