Convert java.util.Date to String
To convert a java.util.Date
object to a String
, you can use the format
method of the SimpleDateFormat
class from the java.text
package. The SimpleDateFormat
class provides a convenient way to convert a Date
object to a String
based on a specified format.
Here's an example of how you can convert a Date
object to a String
using the SimpleDateFormat
class:
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
// Create a Date object
Date date = new Date();
// Create a SimpleDateFormat object with the desired format
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Convert the Date object to a String
String str = sdf.format(date);
// Print the String
System.out.println(str);
}
}
This code will print the current date and time in the format yyyy-MM-dd HH:mm:ss
.
You can specify any format that you want using the SimpleDateFormat
class. For example, to print the date in the format dd/MM/yyyy
, you can use the following code:
SimpleDateFormat sdf = new SimpleDateFormat("dd/