2012-04-16 141 views
1

我已经编写了显示当前时间的代码,但是我的问题是它不会显示am或pm格式的时间,只会显示例如12:00。没有上午或下午上午/下午格式的显示时间

java.util.Calendar thetime = java.util.Calendar.getInstance(); 
    int h = thetime.get(java.util.Calendar.HOUR_OF_DAY); 
    int m = thetime.get(java.util.Calendar.MINUTE); 

    System.out.println("the current time is"+ h +":"+m); 
+0

你发布这个问题之前,你读过日历api吗? – Rajesh 2012-04-16 09:10:14

回答

6

尝试增加:

int a_p = thetime.get(java.util.Calendar.AM_PM); 
String am_pm; 
if(a_p==0) 
    am_pm = "AM"; 
else 
    am_pm = "PM"; 

在你的输出端再加入am_pm

无论如何,你应该更喜欢SimpleDateFormat,试着看看它here

0

使用DateFormatter以字符串格式显示时间。 Here

4

你还是使用SimpleDateFormat

String time = new SimpleDateFormat("h:mm a").format(new Date()); 
1

您可以做手工,例如

String ampm = h > 12 ? "PM" : "AM"; 
// now print the variable ampm 

甚至更​​好的使用SimpleDateFormat。请参考这个类'javadoc学习如何配置它。第一次需要5分钟,然后节省您的时间。

1

当你的servlet打印出唯一的值时,你应该使用DateFormat来设置如何打印值。

举个例子:

DateFormat.getDateInstance(DateFormat.SHORT, <put your locale here>); 

更多信息,请参见DateFormat class here

1

使用calendar.get(Calendar.AM_PM)

它将返回整数值为1,如果当前时间是在下午或者0,其指示AM。 通过这个link ..

相关问题