首页 > 解决方案 > 转换时间(12 小时和 24 小时)

问题描述

我正在编写一个转换时间(12 小时和 24 小时)的程序。我想要得到的结果如下:

convertTime ("12:00") ➞ "0:00"

convertTime ("6:20 pm") ➞ "18:20"

convertTime ("21:00") ➞ "9:00 pm"

convertTime ("5:05") ➞ "5:05"

这是我的代码,不幸的是结果不是我所期望的,事实上:

非常感谢您的帮助,在此先感谢!

public static String convertTime(String time) {
    String hour = time.substring(0, time.indexOf(":"));
    String min = time.substring(3, time.indexOf(":") + 3);

    int hourInteger = Integer.parseInt(hour);

    if (hourInteger > 12 && hourInteger < 24) {
      hourInteger = hourInteger - 12;
    }


    if (hourInteger == 24) {
      hourInteger = 0;
    }
    if (hourInteger < 12) {
      return hourInteger + ":" + min + " AM";
    }
    if (hourInteger > 12)
      return hourInteger + ":" + min + " PM";

    return hourInteger;
  }

标签: javatime

解决方案


您可以使用下面的代码片段,您可以根据需要进行相应的更改。使用 Date API 解析反之亦然 12 <-> 24 小时格式。

    public static String convertTime(String time) throws ParseException {

    if (time.contains("am") || time.contains("pm")) {
        SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm");
        SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a");
        Date date = parseFormat.parse(time);
        return displayFormat.format(date);
    } else {
        SimpleDateFormat parseFormat = new SimpleDateFormat("HH:mm");
        SimpleDateFormat displayFormat = new SimpleDateFormat("hh:mm a");
        Date date = parseFormat.parse(time);
        return displayFormat.format(date);
    }
}

推荐阅读