Signup/Sign In

How to convert Java Date to String

In Java, Date can be converted into String using the several classes for example, DateFormat and Instant class. The DateFormat class provides a method format() that returns a string object. The DateFormat class belongs to the java.text package.

1. By Using format() method

The format() method is a part of DateFormat class which is an abstract class and is used to convert Date into String. The SimpleDateFormat class is a child class of DateFormat class.

Example 1:

Here, the Date is converted into String by using the format() method of SimpleDateFormat class.

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

public class StudyTonight
{    
   public static void main(String [] args)throws Exception
   {  
      Date d = Calendar.getInstance().getTime();  
      DateFormat df = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");  
      String sDate = df.format(d);  
      System.out.println("String in form of Date is : " + sDate);  
  
   }
    
}


Converted String: 2020-27-29 03:27:15

2. By Using the toString() Method

The toString() method of String class is used to get a string object of any type of object. Here, we used toString() to convert date object to string type. See the example below.

package com.studytonight;

import java.util.Date;
public class CoreJava {

	public static void main(String[] args) {
		Date date = new Date();
		String fullDate = date.toString();
		System.out.println(fullDate);
		String dateString = fullDate.substring( 0 , 11 );
		System.out.println(dateString);
		String timeString = fullDate.substring( 11 , 19 );
		System.out.println(timeString);
	}
}


Thu Nov 26 11:54:45 IST 2020
Thu Nov 26
11:54:45

By Using Java 8 java.time Package

If you are working with Java 8 or higher version then use toInstant() method to get instant object which furhter can be used to convert date to string. The Instant class is used to make date object compatable with java 8 or higher version. See the example below.

package com.studytonight;

import java.time.Instant;
import java.util.Date;
public class CoreJava {

	public static void main(String[] args) {
		Date date = new Date();
		Instant instant = date.toInstant();
		String fullDate = instant.toString();
		System.out.println(fullDate);
		String dateString = fullDate.substring( 0 , 10 );
		System.out.println(dateString);
		String timeString = fullDate.substring( 11 , 19 );
		System.out.println(timeString);
	}
}


2020-11-26T06:31:20.445Z
2020-11-26
06:31:20



About the author:
A Computer Science and Engineering Graduate(2016-2020) from JSSATE Noida. JAVA is Love. Sincerely Followed Sachin Tendulkar as a child, M S Dhoni as a teenager, and Virat Kohli as an adult.