In Java, you can use the java.text.SimpleDateFormat
class to format a java.util.Date
object as a string.
Here is an example of how to use the SimpleDateFormat
class to format a Date
object as a string in Java:
import java.text.SimpleDateFormat; import java.util.Date; public class Main { public static void main(String[] args) { // Create a SimpleDateFormat instance SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // Create a Date object Date date = new Date(); // Format the Date object as a string String formattedDate = sdf.format(date); // Print the formatted string System.out.println(formattedDate); // Output: current date and time } }
In this example, we create a SimpleDateFormat
instance and specify a date and time format string using the yyyy
(year), MM
(month), dd
(day), HH
(hour), mm
(minute), and ss
(second) patterns. We then create a Date
object representing the current date and time, and call the format
method on the SimpleDateFormat
instance to format the Date
object as a string.
You can modify the format string to suit your needs. For example, you can use the yyyy-MM-dd
pattern to specify a date-only format, or the HH:mm
pattern to specify a time-only format. Refer to the SimpleDateFormat
documentation for a complete list of patterns.