目前显示的时间为13:35 PM 但是,我想显示为AM/PM的12小时格式,即下午1:35而不是下午13:35

当前代码如下所示

private static final int FOR_HOURS = 3600000;
private static final int FOR_MIN = 60000;
public String getTime(final Model model) {
    SimpleDateFormat formatDate = new SimpleDateFormat("HH:mm a");
    formatDate.setTimeZone(userContext.getUser().getTimeZone());
    model.addAttribute("userCurrentTime", formatDate.format(new Date()));
    final String offsetHours = String.format("%+03d:%02d", userContext.getUser().getTimeZone().getRawOffset()
    / FOR_HOURS, Math.abs(userContext.getUser().getTimeZone().getRawOffset() % FOR_HOURS / FOR_MIN));
    model.addAttribute("offsetHours",
                offsetHours + " " + userContext.getUser().getTimeZone().getDisplayName(Locale.ROOT));
    return "systemclock";
}

当前回答

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss a");

("hh:mm:ss a") >>>这里如果我们不使用'a',那么24hours将会出现。所以如果我们想在你的时间AM/PM播放,只需添加这个格式。如有任何疑问,请告诉我。

其他回答

最简单的方法是使用日期模式- h:mm a,其中

h -上午/下午(1-12点) m -一小时中的一分钟 a -上午/下午标记

代码片段:

DateFormat dateFormat = new SimpleDateFormat("hh:mm a");

阅读更多文档- SimpleDateFormat java 7

    //To get Filename + date and time


    SimpleDateFormat f = new SimpleDateFormat("MMM");
    SimpleDateFormat f1 = new SimpleDateFormat("dd");
    SimpleDateFormat f2 = new SimpleDateFormat("a");

    int h;
         if(Calendar.getInstance().get(Calendar.HOUR)==0)
            h=12;
         else
            h=Calendar.getInstance().get(Calendar.HOUR)

    String filename="TestReport"+f1.format(new Date())+f.format(new Date())+h+f2.format(new Date())+".txt";


The Output Like:TestReport27Apr3PM.txt

使用Java 8:

LocalTime localTime = LocalTime.now();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
System.out.println(localTime.format(dateTimeFormatter));

输出为AM/PM格式。

Sample output:  3:00 PM

使用这个SimpleDateFormat formatDate =新的SimpleDateFormat("hh:mm a");

SimpleDateFormat的Java文档

SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm:ss a");

h表示AM/PM时间(1 ~ 12)。 H表示24小时次数(1 ~ 24次)。 a是AM/PM标记 M是以小时为单位的分钟

注意:两个h将打印前导零:01:13 PM。一个h打印时不带前导零:1:13 PM。

看来大家都抢在我前面了,我跑题了