有没有办法将时间从 "hh:mm:ss" 格式转换为 "hh:mm AM/PM" 格式?
Is there any way of converting time from "hh:mm:ss" format to "hh:mm AM/PM" format?
我在数据库中以这种格式存储时间:"hh:mm:ss"
(示例 - 09:30:00)然后检索并尝试以这种格式向用户显示它:"hh:mm AM/PM"(示例- 09:30 上午)。
我正在使用以下代码进行转换:
DateFormat currentTime = new SimpleDateFormat("hh:mm a");
String startTimeInSF = currentTime.format(startTime);
String endTimeInSF = currentTime.format(endTime);
其中 startTime
和 endTime
是 hh:mm:ss
格式,但是上面的代码产生了这个错误:java.lang.IllegalArgumentException: Bad class: class java.lang.String
.
请告诉我如何将时间从 hh:mm:ss
成功转换为 hh:mm AM/PM
?
我相信您正在寻找 parse(String source) 方法。 format() 方法接收一个 Date 对象并输出该对象的 String 表示形式。 parse 方法接收一个 String 对象并将其转换为 Date 对象。
要执行您想要的操作,您需要使用 hh:mm:ss 的 DateFormat,使用解析将数据库字符串转换为日期,然后使用现有的 DateFormat 并在 Date 对象上使用格式来获取要显示给用户的输出字符串。
http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html
我认为您应该将 "hh:mm:ss" 时间解析为日期对象,然后使用格式化程序将其格式化为 "hh:mm a"。
像这样:
DateFormat format1 = new SimpleDateFormat("hh:mm:ss");
try {
Date date = format1.parse("01:11:22");
SimpleDateFormat format2 = new SimpleDateFormat("hh:mm a");
String result = format2.format(date);
return result;
} catch (ParseException e) {
e.printStackTrace();
}
您需要像这样更改您的代码,格式函数将不能直接作用于 String 对象,这是导致异常的根本原因。
DateFormat inputFormatter1 = new SimpleDateFormat"HH:mm:ss");
Date date1 = inputFormatter1.parse("22:10:11");
DateFormat outputFormatter1 = new SimpleDateFormat("hh:mm a");
String output1 = outputFormatter1.format(date1); //
外出时间为 10:10 下午
我在数据库中以这种格式存储时间:"hh:mm:ss"
(示例 - 09:30:00)然后检索并尝试以这种格式向用户显示它:"hh:mm AM/PM"(示例- 09:30 上午)。
我正在使用以下代码进行转换:
DateFormat currentTime = new SimpleDateFormat("hh:mm a");
String startTimeInSF = currentTime.format(startTime);
String endTimeInSF = currentTime.format(endTime);
其中 startTime
和 endTime
是 hh:mm:ss
格式,但是上面的代码产生了这个错误:java.lang.IllegalArgumentException: Bad class: class java.lang.String
.
请告诉我如何将时间从 hh:mm:ss
成功转换为 hh:mm AM/PM
?
我相信您正在寻找 parse(String source) 方法。 format() 方法接收一个 Date 对象并输出该对象的 String 表示形式。 parse 方法接收一个 String 对象并将其转换为 Date 对象。
要执行您想要的操作,您需要使用 hh:mm:ss 的 DateFormat,使用解析将数据库字符串转换为日期,然后使用现有的 DateFormat 并在 Date 对象上使用格式来获取要显示给用户的输出字符串。
http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html
我认为您应该将 "hh:mm:ss" 时间解析为日期对象,然后使用格式化程序将其格式化为 "hh:mm a"。
像这样:
DateFormat format1 = new SimpleDateFormat("hh:mm:ss");
try {
Date date = format1.parse("01:11:22");
SimpleDateFormat format2 = new SimpleDateFormat("hh:mm a");
String result = format2.format(date);
return result;
} catch (ParseException e) {
e.printStackTrace();
}
您需要像这样更改您的代码,格式函数将不能直接作用于 String 对象,这是导致异常的根本原因。
DateFormat inputFormatter1 = new SimpleDateFormat"HH:mm:ss");
Date date1 = inputFormatter1.parse("22:10:11");
DateFormat outputFormatter1 = new SimpleDateFormat("hh:mm a");
String output1 = outputFormatter1.format(date1); //
外出时间为 10:10 下午