&“%tB&"格式化工作?
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
这意味着我使用的语法是错误的.
我找不到在线说明%tB
格式命令的参考.
有人帮忙澄清一下吗?
预先感谢.
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.
来自 Formatter
文档:
日期/时间-可以应用于能够编码的Java类型 日期或时间:
long
,Long
,Calendar
和Date
.
Date/Time - may be applied to Java types which are capable of encoding a date or time:
long
,Long
,Calendar
, andDate
.
您可以通过使用长整数(例如12L
)摆脱异常.但是请注意,格式化程序期望日期的整数表示形式(即,具有毫秒精度的Unix时间戳).
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).
为了获得所需的内容,您可以尝试在1970年的一个月中手动构建一个近似的时间戳记:
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);
或者简单地使用Date
对象:
System.out.format("%tB", new Date(0, 12, 0));
还请注意,您可以在没有Formatter
的情况下执行相同的操作:
Also note that you can do the same thing without Formatter
:
java.text.DateFormatSymbols.getInstance().getMonths()[12-1];
请参见 DateFormatSymbols
了解更多信息.
See DateFormatSymbols
for more information.