Java Program to Convert Date to String
The date type object can be converted to a string in Java using a large variety of in-built classes available in Java.
Given a date, we need to convert the date to a given format of the string.
Input: date = “2020-11-13”
Input: date = “2020-12-14”
Method 1: Using DateFormat class
- The Calendar class is used to provide functions for carrying out interconversion between any instant in time and a set of calendar fields. The Calendar class has an in-built method getInstance() which is used to fetch the current date and time. It returns the date which is stored in a Date type variable.
- DateFormat class is an in-built class in Java which is used to parse and format date or time values. We can specify the format for the Date using the SimpleDateFormat class object, which takes as an argument the date format and returns the DateFormat specifier.
The DateFormat class has an in-built method format() which has the following syntax :
Returns a string variable corresponding to the date type object provided as an argument to the function.
- Get the date to be converted.
- Create an instance of SimpleDateFormat class to format the string representation of the date object.
- Get the date using the Calendar object.
- Convert the given date into a string using format() method.
- Print the result.
Date to String : 2020-06-12
Method 2: Using SimpleDateFormat class
SimpleDateFormat class is used for formatting and parsing dates. It has an in-built format() method, which can be used to print date in string formats in a variety of ways.
MM/dd/yyyy : 11/12/2020 dd MMMM yyyy zzzz : 12 November 2020 Coordinated Universal Time
Method 3: Using LocalDate.toString() method
- Get an instance of LocalDate from date.
- Convert the given date into a string using the toString() method of LocalDate class.
- Print the result.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.