Java Program To Convert Date To String
Chapter:
Miscellaneous
Last Updated:
11-08-2023 17:12:16 UTC
Program:
/* ............... START ............... */
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateToStringConverter {
public static void main(String[] args) {
// Create a Date object
Date currentDate = new Date();
// Create a SimpleDateFormat object with the desired format
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Convert the Date to a String
String dateString = dateFormat.format(currentDate);
// Print the converted String
System.out.println("Current Date as String: " + dateString);
}
}
/* ............... END ............... */
Output
Current Date as String: 2023-08-11 15:30:45
Notes:
-
Java program demonstrates how to convert a Date object, which represents a point in time, into a human-readable String using a specific format.
- The SimpleDateFormat class is used to define the format in which the date should be displayed as a string. We create a SimpleDateFormat object called dateFormat and provide the desired format pattern as a string: "yyyy-MM-dd HH:mm:ss". This pattern includes placeholders for the year (yyyy), month (MM), day (dd), hours (HH), minutes (mm), and seconds (ss).
- We use the dateFormat object's format method to convert the currentDate into a formatted string according to the pattern. The result is stored in the dateString variable.
- Finally, we print out the converted date string using the System.out.println statement. The output will show the current date and time in the specified format.
Tags
Java program to convert date to string #How to convert a date to a string in Java? #Date to String conversion Java