java.util.Date in Java Example

java.util.Date in Java Example

Date class is inbuilt in Java API and package is java.util.Date.

Date class is used to get the current date, time or specific date time. This has methods to format and parse string dates. Implements Serializable, Cloneable, Comparable<Date>.


java.util.Date in Java Example

Constructor of Date class:


public Date()

Example program to get the current date or today's date:


/**
* @author Java-W3schools Blog
* @File Name Dates.java
*/
package org.java.w3schools.core.dates;

import java.util.Date;

public class Dates {
public static void main(String[] args) {

Date date = new Date();
System.out.println("Current Date and Time :: " + date);
}
}


Output:

Current Date and Time :: Sat Apr 25 13:54:18 IST 2015

Date date = new Date();

This snippet gives us current date time when executed.


Methods of Date class:

1) public boolean after(Date when)


   Tests if this date is after the specified date and throws NullPointerException if "when" is null. true if and only if the instant represented by this Date object is strictly later than the instant represented by when; false otherwise.


2) public boolean before(Date when)

   Tests if this date is before the specified date and throws NullPointerException if "when" is null. true if and only if the instant of time represented by this Date object is strictly earlier than the instant represented by when; false otherwise.

3) public int getDate()

   This is deprecated and replaced by Calendar.set(Calendar.DAY_OF_MONTH, int date). Returns day of the date object. Day will be between 1 and 31.
  
We will see some more methods in the following programs.


Example:




        Date date = new Date();

// Current date is : Sat Apr 25 13:54:18 IST 2015

System.out.println("date.getDate() :: " + date.getDate());

System.out.println("date.getDay() :: " + date.getDay());

System.out.println("date.getHours() :: " + date.getHours());

System.out.println("date.getMinutes() :: " + date.getMinutes());

System.out.println("date.getMonth() :: " + date.getMonth());

System.out.println("date.getSeconds() :: " + date.getSeconds());

System.out.println("date.getTime() :: " + date.getTime());

System.out.println("date.getYear() :: " + date.getYear());




Output:


date.getDate() :: 25
date.getDay() :: 6
date.getHours() :: 14
date.getMinutes() :: 20
date.getMonth() :: 3
date.getSeconds() :: 3
date.getTime() :: 1429951803262
date.getYear() :: 115

0 Comments