Java Date Time Classes

Discussion in 'Java' started by shabbir, Jul 13, 2014.

  1. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    A specific instant in time is represented with millisecond precision by the Date class. Date is interpreted as year, month, day, hour, minute, and second values using this class. But API for functions of this class was not so flexible and hence was not supported at international level. Also for JDK 1.1, some of the methods got deprecated and they are replaced by methods of Calendar class.

    Importance of Date Time Classes in Java



    Date Time class in Java is an essence for java. It helps in accomplishing different important tasks in various programming activities. For example, in an application; we want to keep track of the activities for the registered user. Here we can store login and logout time. These details are very helpful in carrying out various operations (as an account which is idle will be logged out automatically after a particular duration of time or notification to the user to change its password after a particular number of days). These details are very useful for keeping track of the user activities and are very common. Hence this class is used very often.

    Date



    Constructors

    Date()

    Initializes the date object and allocates it to the current date and time.

    public Date(long mills)

    Initializes the date object and allocates it to represent the specified number of milliseconds since the standard base time January 1, 1970, 00:00:00 GMT.

    Parameters:
    • mills - The milliseconds since January 1, 1970, 00:00:00 GMT.
    public Date(int year, int month, int date) - Deprecated

    This method has been replaced by Calendar.set(year + 1900, month, date). Initializes a Date object and allocates it so that it represents local time specified by the year, month, and date arguments.

    Parameters:
    • year - The year minus 1900.
    • month - The month between 0-11.
    • date - The day of the month between 1-31.
    public Date(int year, int month, int date, int hrs, int min, int sec) - Deprecated

    This method has been replaced by Calendar.set(year + 1900, month, date, hrs, min, sec). Allocates a Date object and initializes it; representing the instance specified by the year, month, date, hrs, min, and sec arguments, in the local time zone.

    Parameters:
    • year - The year minus 1900.
    • month - Month ranging between 0-11.
    • date - Day of the month ranging between 1-31.
    • hrs - Hours ranging between 0-23.
    • min - Minutes ranging between 0-59.
    • sec - Seconds ranging between 0-59.
    public Date(String str) - Deprecated

    This method has been replaced by DateFormat.parse(String s). It Initializes a Date object and allocates it which represents the date and time indicated by the string str.

    Parameters:
    • str – Date in String format.
    Methods

    public long getTime()

    It returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

    public void setTime(long time)

    Sets the Date object corresponding to time in milliseconds after January 1, 1970 00:00:00 GMT.

    Parameters:
    • time - The number of milliseconds.
    public boolean before(Date dt)

    This method checks whether the Date object is earlier than the passed instance.

    Parameters:
    • dt - A date instance.
    Returns true if the Date object is earlier than the specified instance represented by when as argument; otherwise it returns false.

    public boolean after(Date dt)

    This method checks whether the Date object is after the specified instance.

    Parameters:
    • dt - A date instance.
    Returns true if the Date object is after the specified instance represented by when as argument; otherwise it returns false.

    public int compareTo(Date d)

    Compares the Date object with the specified date instance.

    Parameters:
    • d - The Date instance to be compared.
    It returns 0 if the argument Date is equal to the Date Object; a value less than 0 if this Date Object is before the Date passed as argument; and a value greater than 0 if it is after the Date passed as argument.

    public int getYear() - Deprecated

    This method is replaced by Calendar.get(Calendar.YEAR) - 1900. It returns a value after subtracting 1900 from the year that is represented by the Date object.

    public void setYear(int year) - Deprecated

    This method is replaced by Calendar.set(Calendar.YEAR, year + 1900). It is used to set the year of Date object adding 1900 in its value. This Date object is modified representing the specified year, with the month, date, hour, minute, and second the same as before.

    Parameters:
    • year - The year value
    public int getMonth() - Deprecated

    It is replaced by Calendar.get(Calendar.MONTH). This method returns a number representing the month of this Date object.

    public void setMonth(int month) - Deprecated

    This method is replaced by Calendar.set(Calendar.MONTH, int month). It is used to set the month of specified date. Modified Date object represents the specified month, with the year, date, hour, minute, and second the same as before.

    Parameters:
    • month - Value of month between 0-11.
    public int getDate() - Deprecated

    As of JDK version 1.1, this method has been replaced by Calendar.get(Calendar.DAY_OF_MONTH).

    Returns the day of the month (value between 1 and 31) represented by this Date object.

    public void setDate(int date) - Deprecated

    This method has been replaced by Calendar.set(Calendar.DAY_OF_MONTH, int date). It is used to set the day of the month of this Date object; with the year, month, hour, minute, and second the same as before.

    Parameters:
    • date - value between 1-31.
    public int getDay() - Deprecated

    This method is replaced by Calendar.get(Calendar.DAY_OF_WEEK). It returns day of the week represented by this date.

    public int getHours() - Deprecated

    This function has been replaced by Calendar.get(Calendar.HOUR_OF_DAY). This method returns the hour represented by this Date object. The returned value represents the hour within the day between 0 and 23.

    public void setHours(int hrs) - Deprecated

    It is replaced by Calendar.set(Calendar.HOUR_OF_DAY, int hours). It is used to set the hour of this Date object to the specified value without any change in the value of year, month, date, minute, and second.

    Parameters:
    • hrs - The hour value as integer.
    public int getMinutes() - Deprecated

    This method has been replaced by Calendar.get(Calendar.MINUTE). Number of minutes past the hour represented by this date is returned between 0 and 59.

    public void setMinutes(int mins) - Deprecated

    This function has been replaced by Calendar.set(Calendar.MINUTE, int minutes). It is used to set the minutes of this Date object to the specified value. This Date object gets modified representing the specified minute, with no change in the value of year, month, date, hour, and second.

    Parameters:
    • mins - The value of the minutes.
    public int getSeconds() - Deprecated

    This method got replaced by Calendar.get(Calendar.SECOND). The method getSeconds() returns the number of seconds past the minute represented by this date from 0 to 59.

    public void setSeconds(int secs) - Deprecated

    The function got replaced by Calendar.set(Calendar.SECOND, int seconds). It sets the seconds of this Date to the specified value; without any change in year, month, date, hour, and minute.

    Parameters:
    • secs – The integer value representing seconds.
    Example
    Code:
    import java.util.*;
    public class DateDemo {
        public static void main(String[]  dt) {
            try {
                // create a date object
                Date date = new Date();
                System.out.println("*****************************************************");
                System.out.println();
                System.out.println("Current Date and Time "+date);
                System.out.println("Current Time in milliseconds "+date.getTime());
                System.out.println();
                System.out.println("*****************************************************");
            }
            catch(Exception e) {
                System.out.println(e);
            }
        }
    }
    
    Output

    [​IMG]

    SimpleDateFormat



    SimpleDateFormat class is used for formatting date to text formats and parsing text to date format. Date patterns can be set as DD/MM/YYYY , MM/DD/YYYY , YYYY-MM-DD , YYYY-MM-DD HH:mm:ss and many more with this class.

    Constructors

    public SimpleDateFormat(String patrn)

    Constructs a SimpleDateFormat based upon the given pattern.

    Parameters:
    • patrn - The pattern describing the date and time format
    In order to format date using SimpleDateFormat, we first needs to define a String date format For Example : "DD-MM-YYYY" will print dates in that format like 11-01-2014. There are lots of patterns for conversion of date and time as described below :
    • "yyyy.MM.dd G 'at' HH:mm:ss z" will display 2014.07.12 AD at 03:35:09 CDT. Here CDT stands for Central Daylight Time
    • "EEE, MMM d, ''yy" will produce Sat, Jul 12, '14
    • "h:mm a" will produce result as 3:38 PM
    • “k:mm a, z” will produce 3:45 AM, CDT
    • "hh 'o''clock' a, zzzz" will show time as 03 o'clock AM, Central Daylight Time
    • "yyyyy.MMMMM.dd GGG hh:mm aaa" will display time as 02014.July.12 AD 03:41 AM
    • "EEE, d MMM yyyy HH:mm:ss Z" will produce result as Sat, 12 Jul 2014 03:42:01 -0500
    • "yyMMddHHmmssZ" will produce 140712034227-0500
    • "yyyy-MM-dd'T'HH:mm:ss.SSSZ" will produce result as 2014-07-12T03:43:14.376-0500
    Example to parse string date value input with SimpleDateFormat("dd-MMM-yy")
    Code:
    import java.text.Format;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    public class SDFDemo {
        public static void main(String[] dt) {
            try {
                Date d = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
                String date = sdf.format(d);
                System.out.println("**************************************************");
                System.out.println();
                System.out.println("Date As Specified in SimpleDateFormat Constructor "+date);
                System.out.println();
                System.out.println("**************************************************");
            }
            catch(Exception e) {
                System.out.println(e);
            }
        }
    }
    Output

    [​IMG]

    Calendar



    The class Calendar is an abstract class that provides methods for conversion between time and calendar fields. It provides methods and fields for implementation of calendar system.
    This class provides a class method, known as getInstance(), that returns a general object of this type, whose calendar fields have been initialized with the current date and time.

    Fields
    • public static final int YEAR - This field is used to get and set the value indicating the year.
    • public static final int MONTH - This field is used to get and set the value indicating the month. The first month of the year in the calendar is JANUARY which is 0.
    • public static final int DATE - This field is used to get and set the value indicating the day of the month. The first day of the month has value 1.
    • public static final int HOUR - This field is used to get and set the value indicating the hour. HOUR is used for the 12-hour clock (0 - 11). Noon and midnight are represented by 0, not by 12. For Example: at 11:14:15.233 AM the HOUR is 11.
    • public static final int MINUTE - This field is used to get and set the value indicating the minute within the hour. For Example: at 05:22:35.120 PM the MINUTE is 22.
    • public static final int SECOND - This field is used to get and set the value indicating the second within the minute. For Example: at 01:06:39.250 PM the SECOND is 39
    • public static final int MILLISECOND - This field is used to get and set the value indicating the millisecond within the second. For Example: at 06:27:11.110 PM the MILLISECOND is 110.
    • Public static final int MILLISECOND - This field is used to get and set the value indicating the millisecond within the second. For Example: at 06:27:11.110 PM the MILLISECOND is 110.
    Constructors

    protected Calendar()

    A protected constructor so no object for the calendar class can be created and getInstance function returns the Calendar object with the default time zone.

    Class methods

    public static Calendar getInstance()

    This method returns the calendar with default time zone.

    public final Date getTime()

    Gets a Date object which represents the Calendar's time value.

    public final void setTime(Date d)

    This method is used to set the Calendar's time with the specified Date d.

    Parameters:
    • d - The Specified Date to be set.

    public final void set(int yr, int mnth, int dt)

    This method is used to set the values for the calendar fields like YEAR, MONTH, and DAY_OF_MONTH. Other values of calendar fields does not change.

    Parameters:
    • yr – YEAR calendar field is set.
    • mnth - MONTH calendar field is set. Here Month value is 0 for January.
    • dt - DAY_OF_MONTH calendar field is set.
    Public final void set(int year,int month,int date,int hour,int min, int sec)

    It is used to set the values for the calendar fields like YEAR, MONTH, DAY_OF_MONTH, HOUR_OF_DAY, and MINUTE. Other values of Calendar remains same.

    Parameters:
    • year - YEAR calendar field is set.
    • month - MONTH calendar field is set.
    • date - DAY_OF_MONTH calendar field is set.
    • hour - HOUR_OF_DAY calendar field is set.
    • min - MINUTE calendar field is set.
    • sec - SECOND calendar field is set.
    Example
    Code:
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    public class CalendarDemo {
        public static void main(String[] dt) {
            SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
            // Get an instance of a Calendar, using the current time.
            Calendar cal = Calendar.getInstance();
            System.out.println("*****************************************************");
            System.out.println();
            System.out.println(sdf.format(cal.getTime()));
            System.out.println("YEAR: " + cal.get(Calendar.YEAR));
            System.out.println("MONTH: " + cal.get(Calendar.MONTH));
            System.out.println("DATE: " + cal.get(Calendar.DATE));
            System.out.println("HOUR: " + cal.get(Calendar.HOUR));
            System.out.println("MINUTE: " + cal.get(Calendar.MINUTE));
            System.out.println("SECOND: " + cal.get(Calendar.SECOND));
            System.out.println();
            System.out.println("****************************************************");
        }
    }
    
    Output

    [​IMG]
     
    Last edited: Jan 21, 2017

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice