Date and Time formatting using Formatter class in java

Viewed 204

I'm stuck in a problem, I know that we can use SimpleDateFormat class or other format classes in java to format the date/time. But I'm trying to format the time and date using Formatter class method format. Is that possible? If yes, then how it is possible?

LocalDate date = LocalDate.now();
Formatter formatter = new Formatter();
formatter.format("%tm/%td/%ty", date);
System.out.println(formatter);

I got java.util.MissingFormatArgumentException: Format specifier '%td'.

1 Answers

You have got three (3) format specifiers (%tm, %td and %ty), so format() immediately expects three arguments in addition to the format string. You gave only one.

The solution is not to repeat the same argument. There are two ways to tell format() to use the same argument again.

One way, give explicit argument index, from 1:

formatter.format("%1$tm/%1$td/%1$ty", date);

Output:

09/10/21

Other way, a < tells format() to use the same argument one more time:

formatter.format("%tm/%<td/%<ty", date);

Output is the same.

Related