我正在尝试使用日历类打印HOUR_OF_DAY,Minute and Second
。
我在代码中使用了以下命令。
System.out.println(
Calendar.HOUR+" "+
Calendar.HOUR_OF_DAY+" "+
Calendar.MINUTE+" "+
Calendar.SECOND+" "
);
它给出的输出如下:
10 11 12 13
即使我运行了几个小时,它也给出了相同的输出。
我以为它会以 24 小时格式打印当前时间。但我没有得到该输出。
所以我想知道这个 HOUR_OF_DAY, HOUR 应该打印什么。
请澄清。
最佳答案
Calendar.HOUR
、Calendar.HOUR_OF_DAY
等只是用于标识日期/时间的各个方面的常量。它们通常这样使用:
Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
我无法轻易想到您想要打印出常量本身的任何情况。
现在,即使您使用它,您仍然会通过字符串连接将 int
值转换为 String
值 - 这不知道您想要什么格式,因为您没有明确指定它。不存在“2 位数字格式 int
”这样的东西...int
只是一个数字。
您应该研究 DateFormat
和 SimpleDateFormat
- 这是使用标准 Java 类库格式化日期和时间的首选方法。 (我个人鼓励您研究 Joda Time 作为更好的日期/时间 API,但这是另一回事。)
例如:
DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
// Prints the current time using 24-hour format
System.out.println(formatter.format(new Date());
关于java - Java 中的日历类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19153609/