Calendar date to yyyy-MM-dd format in java

To format a Calendar date in the yyyy-MM-dd format in Java, you can use the SimpleDateFormat class. Here is an example of how to do this:

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Main {
  public static void main(String[] args) {
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String date = sdf.format(calendar.getTime());
    System.out.println(date);  // Outputs "2023-01-04"
  }
}

This code creates a Calendar object and a SimpleDateFormat object with the pattern "yyyy-MM-dd". It then formats the date in the Calendar object using the format() method of the SimpleDateFormat and prints the result to the console.

The SimpleDateFormat class allows you to specify a variety of date and time formats using pattern letters. In this example, the pattern "yyyy-MM-dd" specifies a four-digit year (yyyy), a two-digit month (MM), and a two-digit day of the month (dd). The resulting string will have the format "yyyy-MM-dd", for example "2023-01-04".