How to format a date to String in Java?

Java 8Object Oriented ProgrammingProgramming

The java.text package provides a class named SimpleDateFormat which is used to format and parse dates in required manner (local).

Using the methods of this class you can parse String to Date or, format Date to String.

Formatting Date to String

You can format a given String to Date object using the parse() method of the SimpleDateFormat class. To this method you need to pass the Date in String format. To format a String to Date object −

  • Instantiate the SimpleDateFormat class by passing the required pattern of the date in String format to its constructor.

//Instantiating the SimpleDateFormat class
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
  • Format/convert the required Date object to String using the format() method, by passing it as a parameter.

//Formatting the obtained date
String formattedDate = formatter.format(date);

Example

Following Java program formats the current date to a String and prints it.

 Live Demo

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
public class DateToString {
   public static void main(String args[]) throws ParseException {
      //Retrieving the current date
      LocalDate localDate = LocalDate.now();
      //Converting LocalDate object to Date
      Date date = java.sql.Date.valueOf(localDate);
      //Instantiating the SimpleDateFormat class
      SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
      //Formatting the obtained date
      String formattedDate = formatter.format(date);
      System.out.println("Formatted date: "+formattedDate);
   }
}

Output

Formatted date: 31-05-2019
raja
Published on 04-Jul-2019 14:38:52
Advertisements