Java convert date to string

Let’s learn java convert date to string.

java convert date to string

Convert date to string java

To convert date to string in java, format() method is used of DateFormat class. Here DateFormat class is abstract class and it’s child class is SimpleDateFormat.

Also read – arrays in java

The syntax and example for format() method is as below,

String format(Date d)

Example:

Date dt = Calendar.getInstance().getTime();

DateFormat df = new SimpleDateFormat(“yyyy-mm-dd hh:mm:ss”);

String strDate = df.format(dt);

Let’s see java code to convert date to string,

import java.text.SimpleDateFormat;
import java.util.Date;

public class FB
{
   public static void main(String[] args)
   { 
      Date dt = new Date(); 
      SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); 
      String strDate = sdf.format(dt); 
      System.out.println("Date format - MM/dd/yyyy : " + strDate); 

      sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss"); 
      strDate = sdf.format(dt); 
      System.out.println("Date format - dd-M-yyyy hh:mm:ss : " + strDate); 

      sdf = new SimpleDateFormat("dd MMMM yyyy"); 
      strDate = sdf.format(dt); 
      System.out.println("Date format - dd MMMM yyyy : " + strDate); 

      sdf = new SimpleDateFormat("dd MMMM yyyy zzzz"); 
      strDate = sdf.format(dt); 
      System.out.println("Date format - dd MMMM yyyy zzzz : " + strDate); 

      sdf = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z"); 
      strDate = sdf.format(dt); 
      System.out.println("Date format - E, dd MMM yyyy HH:mm:ss z : " + strDate); 
   }
}



Output:

Date format - MM/dd/yyyy : 12/18/2018
Date format - dd-M-yyyy hh:mm:ss : 18-12-2018 02:20:35
Date format - dd MMMM yyyy : 18 December 2018
Date format - dd MMMM yyyy zzzz : 18 December 2018 India Standard Time
Date format - E, dd MMM yyyy HH:mm:ss z : Tue, 18 Dec 2018 14:20:35 IST