Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Java

Idiom #99 Format date YYYY-MM-DD

Assign to the string x the value of the fields (year, month, day) of the date d, in format YYYY-MM-DD.

String x = String.format("%1$tY-%1$tm-%1$td", d)

Per documentation (see documentation URL), d may be:

long, Long, java.util.Date, java.util.Calendar, or java.time.temporal.TemporalAccessor (which then includes most java.time types)
import java.text.SimpleDateFormat;
String x = new SimpleDateFormat("yyyy-MM-dd").format(d);

d has type java.util.Date.
A SimpleDateFormat instance may be reused, but is not thread-safe.
import static java.util.Calendar.getInstance;
import java.util.Date;
Date d = getInstance().getTime();
String s = "%tY-%<tm-%<td".formatted(d);
with Ada.Calendar.Formatting;
X : constant String :=
    Ada.Calendar.Formatting.Image (D) (1 .. 10);

The Image function returns time as well therefore the slice.

New implementation...