Date Java

Date Java used in routine coding to store dates in a DS at runtime or writing to a database like employees joining dates or birth dates or to manipulate dates. To do the job, Date class comes with many methods and fields.

Many methods of Date class are deprecated. Designers advice to discontinue using Date class and its place use class Calendar (TimeZone and Locale) and class GregorianCalendar. Date class belongs to JDK 1.0 and Calendar to later version JDK 1.1.

Before going into programming, remember the following information of Date Java.
  1. Add 1900 (known as epoch year) to the year returned by the Date class to get the correct year. That is, for 2011, the date returns 111.
  2. Months are numbered to 0 to 11. That is 0, returned by the Date class, should be learnt as January.
  3. Month dates are numbered 1 to 31.
  4. Hours are given as 0 to 23. The early morning 1.00 AM is returned as 0.0 hour.
  5. Minutes are numbered as 0 to 59.
  6. Seconds are printed as 0 to 60 (if 61 is printed, think it is a leap second).

Following is the class signature as defined in the java.util package.

public class Date extends Object implements Serializable, Cloneable, Comparable

Following program explains a few class Date Methods.

import java.util.Date;
public class DateInfo
{
  public static void main(String args[])
  {
    Date today = new Date();
    System.out.println("Today Particulars: " + today);
    System.out.println("Hours Part of today: " + today.getHours());
    System.out.println("Minutes part of today: " + today.getMinutes());
    System.out.println("Seconds part of today: " + today.getSeconds());  			
    System.out.println("Month part of today: " + today.getMonth());
    System.out.println("Date part of today: "  + today.getDate());
    System.out.println("Day part of today: " + today.getDay());
    System.out.println("Year part of today: " + today.getYear());
    System.out.println("Milliseconds representation of today (from epoch time 01-01-1900: " + today.getTime());
  }
}

Date Java

The month is printed as 0; it is January (0+1). The day 3 means, Wednesday. The year 111 means 2011.

Observe the compilation warning message in the screenshot. It is a deprecation warning and an advice not use Date class and use Calendar class.

===================Extra Reading=============================

A. Basic Programs

1. class Date
2. class Calendar (TimeZone and Locale)
3. class GregorianCalendar

B. Conversions between java.util.Date, java.util.Calendar and java.sql.Date

1. Date Calendar Conversions

Leave a Comment

Your email address will not be published.