How To Get Date without Time in Java

In this tutorial, we will be discussing the problem of how to get a date without time in java. Also, we will be displaying the date in a formatted way.

We will be understanding how the process gets worked and which all packages to import.

Program to Get Date Without Time in Java

In this program, we will be getting the date without the time class.

Initially, we will be importing “java.util.date” package.

Basically, this represents date and time in java. It provides constructors and required methods to deal with problems related to time and date.

Some of the methods include boolean before(Date date) for testing if the current date is before the given date, int compareTo(Date date) which compares the current date with any given date, etc.

Also, we imported “java.text.SimpleDateFormat” which provides particular methods for formatting and parsing date and time in java.

This is a concrete kind of class which is initially inherited from “java.text.DateFormat” class.

After importing the above packages, inside the main block, we create an instance of “SimpleDateFormat” named “formatter”.

We passed a pattern parameter to use for parsing and formatting of dates.

Now we created an object of the “Date” class which represents a specific instant in time.

Now since we have got the date, now is the turn to make it in a formatted manner.

For this purpose, we will use “formatter. format”.

Arguments that are passed are referenced by format specifiers in the format string.

Below is the program for getting the date without time in java:

import java.text.SimpleDateFormat;
import java.util.Date;
public class CurrentDate
{
  public static void main(String[] args) 	
  {
    SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    Date date = new Date();
    System.out.println(formatter.format(date));
  }
}

After the compilation of the above code, we would be getting our desired output with date in a formatted manner. (Note that you have to enter a valid date, you can learn How to check if the given date is valid or not in Java )

Below is Sample output for the above program:

 

How To Get Date without Time in Java

Leave a Reply

Your email address will not be published. Required fields are marked *