Date class

In this chapter you will learn:

  1. What is Java Date class used for
  2. How to create Date object

Java Date class

The class Date represents a specific instant in time, with millisecond precision.

The following representations are used when accepting or returning year, month, date, hours, minutes, and seconds values.

  • A year y is represented by the integer y - 1900.
  • A month is represented by an integer from 0 to 11; 0 is January, 11 is December.
  • A date (day of month) is represented by an integer from 1 to 31 in the usual manner.
  • An hour is represented by an integer from 0 to 23. hour from midnight to 1 a.m. is hour 0, and the hour from noon to 1 p.m. is hour 12.
  • A minute is represented by an integer from 0 to 59.
  • A second is represented by an integer from 0 to 61; the values 60 and 61 occur only for leap seconds.

A date may be specified as January 32 and is interpreted as meaning February 1.

Create Date object

  • Date() creates a Date and initializes it with the current time
  • Date(long date) creates a Date and initializes it to represent the specified number of milliseconds since January 1, 1970, 00:00:00 GMT.
import java.util.Date;
//from  j  av  a2  s . c o m
public class Main{
  public static void main(String args[]) {
    Date date = new Date();

    System.out.println(date);

    long msec = date.getTime();
    System.out.println("Milliseconds since Jan. 1, 1970 GMT=" + msec);
  }
}

The output:

The following code creates java Date from specific time.

import java.util.Date;
/*from ja v a  2 s .co  m*/
import java.util.Date;

public class Main {
  public static void main(String[] args) {
    Date d = new Date(365L * 24L * 60L * 60L * 1000L+99999999L);
    System.out.println(d);
  }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. Methods to compare two dates
  2. Compare two Java Date objects using compareTo method