Java 有没有办法把时间从“时间”转换成“时间”;hh:mm:ss“;格式为“;hh:mm AM/PM“;格式?

Java 有没有办法把时间从“时间”转换成“时间”;hh:mm:ss“;格式为“;hh:mm AM/PM“;格式?,java,android,time,date-format,simpledateformat,Java,Android,Time,Date Format,Simpledateformat,我以以下格式在数据库中存储时间:“hh:mm:ss”(示例-09:30:00),然后检索并尝试以以下格式向用户显示时间:“hh:mm am/PM”(示例-09:30 am) 我正在使用以下代码进行转换: DateFormat currentTime = new SimpleDateFormat("hh:mm a"); String startTimeInSF = currentTime.format(startTime); String endTimeInSF = currentTime.for

我以以下格式在数据库中存储时间:
“hh:mm:ss”
(示例-09:30:00),然后检索并尝试以以下格式向用户显示时间:“hh:mm am/PM”(示例-09:30 am)

我正在使用以下代码进行转换:

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

我相信您正在寻找解析(字符串源)方法。format()方法接收日期对象并输出该对象的字符串表示形式。解析方法接收字符串对象并将其转换为日期对象

要执行所需操作,您需要使用hh:mm:ss的DateFormat,使用parse将数据库字符串转换为日期,然后使用现有的DateFormat和Date对象上的format来获取要向用户显示的输出字符串


我认为应该将“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();
    }

您需要像这样更改代码,format函数将不会直接作用于字符串对象,这是异常的根本原因

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 tt”@prasanakumarj失败!产生此错误:
java.lang.IllegalArgumentException:未知模式字符“t”
您需要一个
SimpleDataFormat
从原始格式解析日期,另一个
SimpleDataFormat
将结果格式化为新格式。发布前搜索堆栈溢出。