java convert date to string

java

In Java, you can use the SimpleDateFormat class to convert a Date object to a string. SimpleDateFormat is a class that can be used to parse and format dates according to a given format string.

Here’s an example of how you can use SimpleDateFormat to convert a Date object to a string:

import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
  public static void main(String[] args) {
    // Set up the SimpleDateFormat object
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    // Create a Date object
    Date date = new Date();
    
    // Format the date using the format method
    String dateString = sdf.format(date);
    System.out.println(dateString);  // Outputs something like "2022-07-03 15:23:01"
  }
}

This code will create a Date object for the current date and time, and then format it using the format string “yyyy-MM-dd HH:mm:ss”, producing a string like “2022-07-03 15:23:01”.

You can also use the java.time package, introduced in Java 8, to format dates and times. The java.time package includes the LocalDate and LocalDateTime classes, which can be used to represent a date and a date and time, respectively, without a time zone. You can use the format method of these classes to format a LocalDate or LocalDateTime object as a string.