Simple Date example

In this section we have presented a simple Date example that shows how you can use different constructors of Date.

Simple Date example

In this section we have presented a simple Date example that shows how you can use different constructors of Date.

Simple Date example

Simple Date example

     

In this section we have presented a simple Date example that shows how you can use different constructors of Date. We can construct the Date class in a number of ways. Here we will be showing few ways to construct the Date object.

  • Default constructor :- Date() creates a Date object and initialize it with the current date and time at which time it was initialized.
  • Parameterized constructor :- Date(int year,int month,int day) creates a Date object and initialize it with given year+1900,  given month and given day.

Date newDate = new java.util.Date(); creates a new instance of Date.

Date newDate = new java.util.Date(99,8,7); creates a new instance of Date with the year value 1999, month value 8 and day value 7.

Here is the example code of SimpleDate.java as follows:

SimpleDate.java

import java.util.Date;

public class SimpleDate
{
  public static void main(String args[]){
    // Creating date with the use of default constructor
    Date newDate = new java.util.Date();
    System.out.println("Create date via Default constructor ==>"+newDate);

    // Creating date with the use of parameterized constructor
    newDate = new java.util.Date(99,8,7);
    System.out.println("Create date via Parameterized constructor ==>"+newDate);
  }
}

Save SimpleDate.java and compile it with the javac command.

Output:

C:\DateExample>javac SimpleDate.java
Note: SimpleDate.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.

C:\DateExample>java SimpleDate
Create date via Default constructor ==>Fri Oct 10 12:09:15 GMT+05:30 2008
Create date via Parameterized constructor ==>Tue Sep 07 00:00:00 GMT+05:30 1999

Download Source Code