How to Convert Date to String in Java
How to Convert Date to String in Java
We need to convert Date to String in Java may for displaying purpose. We can convert Date to String in Java using the format() method of java.text.DateFormat class.
There are following steps to convert Date to String:
- Create an instance of SimpleDateFormat class and parse the date format as an argument.
- Invoke the format() method of SimpleDateFormat class by passing Date as an object. It returns the String representation of date into specified date format.
Remember
There is a little bit confusion between “m” and “M,” “m” represents minutes while “M” represents Month. Similarly “d” represents a date in the month while “D” represents Day of the week. This is the most common cause of error while converting Date to String. In short, ddMMyy is not equal to DDmmyy.
format() method of DateFormat class
This method is used to convert Date into String. DateFormat is an abstract class. SimpleDateFormat is the child class of DateFormat class. The signature of the method is given below:
String format(Date d)
Example
In the following example, we are creating an instance of SimpleDateFormat class used for formatting the string representation of the date (MM/dd/yyyy). The Calendar is an abstract class, so we cannot use the constructor to create an instance. Instead we use the static method Calendar.getInstance() to instantiate a sub-class. It returns a calendar instance based on the current time. The getTime() is the method of Date class belongs to the java.util package. It returns the milliseconds since date. By using the format() method, we can create a String representation of a date with the defined format. The println statement prints the string representation of the date.
import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Calendar; public class DateToStringExample { public static void main (String args[]) { DateFormat Datefrmt = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); Date today = Calendar.getInstance().getTime(); String strDate = Datefrmt.format(today); System.out.println("Converted String is: " +strDate); } }
Output
Converted String is: 05/23/2019 13:46:59