将一串时间转换为24小时格式 [英] convert a string of time to 24 hour format
问题描述
我有一个字符串
以这种格式保存开始时间和结束时间上午8:30 - 晚上9:30
我希望能够删除 AM -
和 PM
并将所有时间转换为24小时格式所以晚上9:30
真的是 21:30
并且两个时间都存储在两个不同的变量中,我知道如何将字符串剥离到子字符串
但我不确定转换,这是我到目前为止。时间变量开始时持有上午8:30 - 下午9:30
。
I have a string
holding a start time and an end time in this format 8:30AM - 9:30PM
I want to be able to strip out the AM -
and the PM
and convert all the times to 24 hour format so 9:30PM
would really be 21:30
and also have both the times stored in 2 different variables, I know how to strip the string into substrings
but Im not sure about the conversion, this is what I have so far. the time variable starts out holding 8:30AM - 9:30PM
.
String time = strLine.substring(85, 110).trim();
//time is "8:30AM - 9:30PM"
String startTime;
startTime = time.substring(0, 7).trim();
//startTime is "8:30AM"
String endTime;
endTime = time.substring(9).trim();
//endTime "9:30AM"
推荐答案
工作代码(考虑到你设法拆分字符串):
Working code (considering that you managed to split the Strings):
public class App {
public static void main(String[] args) {
try {
System.out.println(convertTo24HoursFormat("12:00AM")); // 00:00
System.out.println(convertTo24HoursFormat("12:00PM")); // 12:00
System.out.println(convertTo24HoursFormat("11:59PM")); // 23:59
System.out.println(convertTo24HoursFormat("9:30PM")); // 21:30
} catch (ParseException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
}
// Replace with KK:mma if you want 0-11 interval
private static final DateFormat TWELVE_TF = new SimpleDateFormat("hh:mma");
// Replace with kk:mm if you want 1-24 interval
private static final DateFormat TWENTY_FOUR_TF = new SimpleDateFormat("HH:mm");
public static String convertTo24HoursFormat(String twelveHourTime)
throws ParseException {
return TWENTY_FOUR_TF.format(
TWELVE_TF.parse(twelveHourTime));
}
}
现在考虑一下,SimpleDateFormat , H h K k
可能令人困惑。
Now that I think about it, SimpleDateFormat, H h K k
can be confusing.
干杯。
这篇关于将一串时间转换为24小时格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!