java - 转换时间(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"
这是我的代码,不幸的是结果不是我所期望的,事实上:
12 小时的时间输入将用 am 或 pm 后缀表示。
24 小时的输入时间不包含后缀。
非常感谢您的帮助,在此先感谢!
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;
}
解决方案
您可以使用下面的代码片段,您可以根据需要进行相应的更改。使用 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);
}
}
推荐阅读
- python - 用函数处理文件?
- css - 您可以将 sass 正则表达式选择器应用于样式值吗?
- sql - 用过滤值查询同一张表
- neo4j - Neo4j apoc.path.subgraphAll 返回过滤掉的关系
- javascript - 清除后如何继续setinterval功能
- c - 使用线程写入文件(WINAPI)
- javascript - 如何在最小值、最大值上使用小数百分比格式化 Google Chart Gauge?
- dropbox - Dropbox API - 创建文件夹时添加文件夹概览
- spring-boot - 为什么hibernate在初始化的子句中执行sql
- spring-boot - MockMvc 测试总是为获取请求返回状态码 200