How to convert Date to String in Java
Last Updated :
07 May, 2023
Given a date, the task is to write a Java program to convert the given date into a string.
Examples:
Input: date = “2020-07-27”
Output: 2020-07-27
Input: date = “2018-02-17”
Output: 2018-02-17
Approach:
- 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.
Below is the implementation of the above approach:
Java
import java.util.Calendar;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
class GFG {
public static String
convertDateToString(String date)
{
DateFormat df = new SimpleDateFormat(date);
Date today = Calendar.getInstance()
.getTime();
String dateToString = df.format(today);
return (dateToString);
}
public static void main(String args[])
{
String date = "07-27-2020" ;
System.out.print(
convertDateToString(date));
}
}
|
Approach:
- 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:
Java
import java.time.LocalDate;
class GFG {
public static String
convertDateToString(String date)
{
LocalDate givenDate = LocalDate.parse(date);
String dateToString
= givenDate.toString();
return (dateToString);
}
public static void main(String args[])
{
String date = "2020-07-27" ;
System.out.print(
convertDateToString(date));
}
}
|
Method 3: Using DateTimeFormatter.format() method
Approach:
- Get an instance of LocalDate from date.
- Create a DateTimeFormatter object to format the LocalDate object as a string.
- Use the format() method of the DateTimeFormatter object to convert the LocalDate object to a string.
- Print the result.
Below is the implementation of the above approach:
Java
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
class GFG {
public static String
convertDateToString(String date)
{
LocalDate givenDate = LocalDate.parse(date);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "yyyy-MM-dd" );
String dateToString = givenDate.format(formatter);
return (dateToString);
}
public static void main(String args[])
{
String date = "2022-12-31" ;
System.out.print(
convertDateToString(date));
}
}
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...