Menu
Topics Index
...
`


More Utility Classes >
Siva Nookala - 15 Apr 2016
Date class is available in java.util package, it represents a specific instant of time, with millisecond precision. Date allows the interpretation of dates as year, month, day, hour, minute, and second values. It also allows the formatting and parsing of date strings.

Date Constructors:
ConstructorDescription
Date()Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.
Date(long date)Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

Date Methods:
MethodDescription
boolean after(Date date)Tests if this date is after the specified date.
boolean before(Date date)Tests if this date is before the specified date.
Object clone()Return a copy of this object.
int compareTo(Date date)Compares two dates for ordering.
boolean equals(Object date)Compares two dates for equality.
long getTime()Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
int hashCode()Returns a hash code value for this object.
void setTime(long time)Sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT.
String toString()Converts this Date object to a String.

Simple Date Format Codes:
CharacterDescriptionExample
yYear in four digits2013
MMonth in a yearJuly or 07
dDay in a month10
hHour in A.M./P.M. (1~12)12
HHour in day (0~23)22
mMinute in hour30
sSecond in minute56
SMillisecond234
EDay in weekFriday
DDay in year364
FDay of week in month2 (second Wed. in July)
wWeek in year40
WWeek in month1
aA.M./P.M. markerPM
kHour in day (1~24)23
KHour in A.M./P.M. (0~11)10
zTime zoneEastern Standard Time
'Escape for textDelimiter
"Single quote'
GEra designatorAD

Date Example
import java.util.*;

class DateExampleTest
{
    public static void main(String arg[])
    {
        try
        {
            // Get current date and time
            Date date = new Date(); // LINE A
            System.out.println(date);
            // Convert Date to String.
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss"); // LINE B
            String stringDate = dateFormat.format(date); // LINE C
            System.out.println(stringDate);
            // Convert String to Date.
            SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
            String dateInString = "15/08/1947 02:25:56";
            date = df.parse(dateInString); // LINE D
            System.out.println(date);
        } catch (Exception e)
        {
            e.printStackTrace();
        }    
    }
}
OUTPUT

Fri Apr 18 14:25:43 IST 2014
18/04/2014 02:25:43
Fri Aug 15 02:25:56 IST 1947

DESCRIPTION

In this program, at LINE A we are getting the current date and time. At LINE C we are converting date to string format and string to date format at LINE D by using SimpleDateFormat at LINE B and Date class. The output varies as the time various so it need not be same as the present output.

THINGS TO TRY
  • Replace the code at LINE A with below shown code and see the difference in output.
    SimpleDateFormat dateFormat = new SimpleDateFormat("E MMM yyyy H:mm:s:S:a");
    In the above code E represents Day in Week i.e. (Fri, Mon) depending upon the Day in week.
    MMM represents month in string i.e. (Jan, Feb, Dec) depending upon the month specified in the given date.
    yyyy represents the year. H represents hour in a day i.e. from (0~23).
    s represents seconds.
    S represents milliseconds.
    a is to represent meridian i.e. AM/PM.
  • Replace code at LINE A with code below.
    SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm");
    The output should produce hours and minutes of the particular date.

Date Methods
import java.text.SimpleDateFormat;
import java.util.Date;

class DateMethodTest
{
    public static void main(String arg[])
    {
        try
        {
            Date date1 = new Date(); // LINE A
            // Current date is stored in date1
            String dateInString = "15-08-1947 02:25:56";
            SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            Date date2 = df.parse(dateInString); // LINE B
            System.out.println("The date1 is after date2 : " + date1.after(date2));
            System.out.println("The date2 is before date1 : " + date2.before(date1));
            Date date3 = (Date) date1.clone();
            // Copies date1 into date3
            System.out.println(date1.compareTo(date3)); // LINE C
            // Prints 0
            System.out.println(date1.compareTo(date2)); // LINE D
            // Prints 1
            System.out.println("The date3 is equals to date1 : " + date3.equals(date1));
            System.out.println("Milli second for date1 : " + date1.getTime());
            System.out.println("Hash code for date1 : " + date1.hashCode());
            System.out.println("The date1 before setTime : " + date1);
            date1.setTime(10000); // LINE E
            System.out.println("The date1 after setTime : " + date1);
            String dateString = date1.toString(); // LINE F
            System.out.println("The string form of date1 : " + dateString);
        } catch (Exception e)
        {
            e.printStackTrace();
        }    
    }
}
OUTPUT

The date1 is after date2 : true
The date2 is before date1 : true
0
1
The date3 is equals to date1 : true
Milli second for date1 : 1397812350984
Hash code for date1 : 1947980109
The date1 before setTime : Fri Apr 18 14:42:30 IST 2014
The date1 after setTime : Thu Jan 01 05:30:10 IST 1970
The string form of date1 : Thu Jan 01 05:30:10 IST 1970

DESCRIPTION

In this program, At LINE A current date is stored in date1 and at LINE B the value of String dateInstring is stored in date2. The after, before, clone, compareTo, equals, getTime, hashCode, setTime() and toString methods are applied on these two dates, compareTo returns 0 if they are same else 1. The output varies as the time various so it need not be same as the present output for current date.

THINGS TO TRY
  • Try with the below code which prints current date and time.
    Date date = new Date();
    System.out.println(date);
  • Format a string to Date of format day/month/year(13/03/14).
    SimpleDateFormat sdf = new SimpleDateFormat("d/MM/yyyy");
    String dateNew = sdf.format(date);
    System.out.println(dateNew);
  • Compare two dates 1/1/1990 and 31/1/1990 using compareTo method which is shown at LINE C in the above example.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.