Java中12小时制时间转换为24小时制
本文介绍如何使用Java的SimpleDateFormat
类将12小时制时间格式转换为24小时制。SimpleDateFormat
类的parse()
方法用于解析12小时制时间字符串,format()
方法则将解析后的时间对象格式化为24小时制字符串。
代码示例:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.ParseException;
public class TimeConverter {
public static void main(String[] args) throws ParseException {
// 定义12小时制和24小时制的格式
SimpleDateFormat twelveHourFormat = new SimpleDateFormat("hh:mm a");
SimpleDateFormat twentyFourHourFormat = new SimpleDateFormat("HH:mm");
// 12小时制时间字符串
String twelveHourTime = "10:30 PM";
// 解析12小时制时间字符串
Date date = twelveHourFormat.parse(twelveHourTime);
// 将时间格式化为24小时制
String twentyFourHourTime = twentyFourHourFormat.format(date);
// 打印结果
System.out.println(twelveHourTime + " = " + twentyFourHourTime);
}
}
输出:
10:30 PM = 22:30
相关文档:
请注意,以上代码处理了ParseException
异常,这是因为parse()
方法可能会抛出此异常,如果输入的时间字符串格式不正确。 为了更健壮的代码,可以添加更详细的异常处理。