Current Date Java

How to get the current date Java? Many ways are discussed in the next programs. System class also contains the static method currentTimeMillis() to support system time.

Te constructor of Date class form java.util package can be used to get the system date or current date. The Date class methods are deprecated and means not advised to use. In its place usage of java.util.Calendar class, introduced with JDK 1.1, is suggested by Designers.

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

public class Date extends Object implements Serializable, Cloneable, Comparable

Next example uses Date class methods to get current date Java.
import java.util.Date;
public class CurrentDate
{
  public static void main(String args[])
  {
    Date currentDate = new Date();
    System.out.println("What is current date?: " + currentDate);
    System.out.println("Hours Part of current date: " + currentDate.getHours());
    System.out.println("Minutes part of current date: " + currentDate.getMinutes());
    System.out.println("Seconds part of current date: " + currentDate.getSeconds());  			
    System.out.println("Month part of current date: " + currentDate.getMonth());
    System.out.println("Date part of current date: "  + currentDate.getDate());
    System.out.println("Day part of current date: " + currentDate.getDay());
    System.out.println("Year part of current date: " + currentDate.getYear());
    System.out.println("Milliseconds representation of current date (from epoch time 01-01-1900: " + currentDate.getTime());
  }
}

Current Date JavaOutput screenshot on Current Date Java

To use with Date class methods, following information to be taken care of.

  1. getYear() returns year from epoch year. The epoch year is 1900. Add 1900 to the year returned by getYear().
  2. getMonth() returns one less as months are numbered 0 t0 11. That is for January, it returns 0. So, add 1 to the month returned by getMonth().
  3. getDate() no problem as dates are numbered 1 to 31.
  4. Hours are numbered 0 to 23. So, add 1 to the hours returned by getHours()
  5. Minutes are given 0 to 59. Add 1 to the minutes returned by getMinutes().
  6. Seconds are numbered 0 to 60 (61 printed for leap second).
import java.util.Date;
public class CurrentDate
{
  public static void main(String args[])
  {
    long currentDate = System.currentTimeMillis();
    System.out.println("Current date in milleseconds: " + currentDate);

    Date today = new Date(currentDate);

    System.out.println("Current date in general format: " + today);
  }
}

Current Date JavaOutput screenshot on Current Date Java

Other ways can be seen in the following links.

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

Refer for conversions between java.util.Date, java.util.Calendar and java.sql.Date

Leave a Comment

Your email address will not be published.