&“%tB&"格式化工作? [英] How does "%tB" formatter work?

查看:102
本文介绍了&“%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类型 日期或时间:longLongCalendarDate.

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

您可以通过使用长整数(例如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.

这篇关于&“%tB&"格式化工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆