How does “%tB” formatter work?

孤街浪徒 提交于 2019-12-10 21:07:38

问题


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.


回答1:


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.




回答2:


A sample prog

import java.util.Calendar;
import java.util.Formatter;

public class MainClass {
  public static void main(String args[]) {
    Formatter fmt = new Formatter();
    Calendar cal = Calendar.getInstance();

    fmt.format("Today is day %te of %<tB, %<tY", cal);
    System.out.println(fmt);
  }
}


来源:https://stackoverflow.com/questions/16232447/how-does-tb-formatter-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!