java date format

java

In Java, you can use the SimpleDateFormat class to format dates. This class is used to parse and format dates according to a given format string.

Here’s an example of how you can use SimpleDateFormat to format a date:

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 a desired format string
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    // Format the date using the format method and print the result
    String formattedDate = sdf.format(date);
    System.out.println(formattedDate);
  }
}

This will print the current date and time in the format “yyyy-MM-dd HH:mm:ss”, which looks like “2022-07-03 15:23:01”.

The format string that you pass to SimpleDateFormat can contain various different patterns to specify how you want the date to be formatted. Some common patterns include:

  • yyyy: 4-digit year
  • MM: 2-digit month (01-12)
  • dd: 2-digit day of the month (01-31)
  • HH: 2-digit hour in 24-hour format (00-23)
  • mm: 2-digit minute (00-59)
  • ss: 2-digit second (00-59)

You can find a full list of available patterns in the documentation for SimpleDateFormat.