目前显示的时间为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";
}

当前回答

使用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 dateFormat = new SimpleDateFormat("dd-MMM-yy hh.mm.ss.S aa");
String formattedDate = dateFormat.format(new Date()).toString();
System.out.println(formattedDate);

输出: 9月11日-13日下午12.25.15.375

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

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

输入当前移动日期和时间格式

2018年2月9日晚10:36:59

Date date = new Date();
 String stringDate = DateFormat.getDateTimeInstance().format(date);

你可以显示它到你的活动,片段,CardView, ListView任何地方使用TextView

` TextView mDateTime;

  mDateTime=findViewById(R.id.Your_TextViewId_Of_XML);

  Date date = new Date();
  String mStringDate = DateFormat.getDateTimeInstance().format(date);
  mDateTime.setText("My Device Current Date and Time is:"+date);

  `

用“hh:mm a”代替“hh:mm a”。这里hh表示12小时格式,hh表示24小时格式。

现场演示

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

SimpleDateFormat的Java文档