【发布时间】:2021-02-16 22:57:57
【问题描述】:
我想将“9:00 am – 11:00 pm”转换为“9:00 - 23:00”,我该怎么做?到目前为止我尝试过的:
if(input.contains("am")) { //This because I have a string with other kind of items too (not only these interval of hours but names, etc)
DateFormat df = new SimpleDateFormat("h:mm a – h:mm a");
DateFormat outputformat = new SimpleDateFormat("HH:mm - HH:mm");
Date date = null;
String output = null;
date= df.parse(input);
input = outputformat.format(date);
System.out.println("Output: "+output);
}
但输出错误,在示例中是 23:00 - 23:00,因为它无法识别第一个小时和第二个小时
我也试过类似的东西:
DateFormat df = new SimpleDateFormat("h:mm a" +" - "+ "h:mm a");
DateFormat outputformat = new SimpleDateFormat("HH:mm"+" - "+ "HH:mm");
但是我得到了一个解析错误
【问题讨论】:
-
从外观上看,输出应该是
null(因为您打印的是output,它只定义为String output = null),所以请发布一些实际重现问题的内容。 -
你传递给
parse方法的string变量是什么!? -
对不起,这不是 date= df.parse(string);但是 date= df.parse(input);如果我在正确获得类型为“9:00 am – 11:00 pm”的字符串列表之后插入一个 println。 if 工作正常 我使用当前代码的输入和输出示例: I/System.out:输入 9:00 am – 11:00 pm I/System.out:输出:23:00 - 23:00 I/System .out:输入:上午 8:00 - 下午 5:00 I/System.out:输出:17:00 - 17:00 I/System.out:输入:上午 4:00 - 下午 12:00 I/系统。出: 输出: 12:00 - 12:00
-
我建议你不要使用
SimpleDateFormat和Date。这些类设计不佳且早已过时,尤其是前者,尤其是出了名的麻烦。而是使用来自java.time, the modern Java date and time API 的LocalTime和DateTimeFormatter。 -
感谢您的澄清。请将其添加到问题本身而不是评论中,以便我们将所有内容集中在一个地方。
标签: java android string date converters