【问题标题】:Is there any way of converting time from "hh:mm:ss" format to "hh:mm AM/PM" format? [duplicate]有没有办法将时间从“hh:mm:ss”格式转换为“hh:mm AM/PM”格式? [复制]
【发布时间】:2016-11-23 02:02:40
【问题描述】:

我以这种格式将时间存储在数据库中:"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);

其中startTimeendTimehh:mm:ss 格式,但上面的代码会产生这个错误:java.lang.IllegalArgumentException: Bad class: class java.lang.String

请告诉我如何才能成功地将时间从hh:mm:ss 转换为hh:mm AM/PM

【问题讨论】:

  • 试试这个“hh:mm tt”
  • @PrasannaKumarJ 失败!产生了这个错误:java.lang.IllegalArgumentException: Unknown pattern character 't'
  • 您需要一个SimpleDateFormat 将您的日期从原始格式解析,另一个SimpleDateFormat 将结果格式化为新格式。
  • 发帖前搜索 Stack Overflow。

标签: java android time date-format simpledateformat


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我相信您正在寻找 parse(String source) 方法。 format() 方法接受一个 Date 对象并输出该对象的 String 表示。 parse 方法接受一个 String 对象并将其转换为 Date 对象。

    要做你想做的事,你需要有一个带 hh:mm:ss 的 DateFormat,使用 parse 将数据库字符串转换为 Date,然后使用你现有的 DateFormat 并在 Date 对象上使用 format 来获取输出字符串以显示给您的用户。

    http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html

    【讨论】:

      【解决方案3】:

      您需要像这样更改您的代码,格式函数将不能直接作用于 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 出发

      【讨论】:

        猜你喜欢
        • 2013-09-09
        • 1970-01-01
        • 2013-04-11
        • 2018-07-20
        • 1970-01-01
        • 2021-02-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多