Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does "%tB" formatter work?

System.out.format("%tB",12);

I should get a "December" out of it, however i get a nice exception

Exception in thread "main" java.util.IllegalFormatConversionException: b != java.lang.Integer

It means the syntax I used is wrong. I cannot find any reference on line explaining the %tB formatting command. Is anybody help to clarify the matter? Thanks in advance.

like image 277
Rollerball Avatar asked Mar 25 '23 04:03

Rollerball


1 Answers

From the Formatter documentation:

Date/Time - may be applied to Java types which are capable of encoding a date or time: long, Long, Calendar, and Date.

You can get rid of the exception by using a long integer such as 12L. But note that the formatter is expecting an integer representation of a date (i.e. a Unix timestamp with millisecond precision).

In order to get what you want, you can try to manually build an approximate timestamp in a middle of a month in 1970 :

int month = 12;
int millisecondsInDay = 24*60*60*1000;
long date = ((month - 1L)*30 + 15)*millisecondsInDay;
System.out.format("%tB", date);

Or simply use a Date object :

System.out.format("%tB", new Date(0, 12, 0));

Also note that you can do the same thing without Formatter :

java.text.DateFormatSymbols.getInstance().getMonths()[12-1];

See DateFormatSymbols for more information.

like image 160
zakinster Avatar answered Apr 06 '23 01:04

zakinster