我需要将时间24小时格式显示为12(am / pm)小时格式

时间:2018-05-31 05:59:54

标签: java android

在此代码中显示错误时间,如果是12:01:00,则显示12:00 AM,但正确的时间是12:00 PM:

private static final String sourceFormat = "hh:mm:ss";
private static final String targetFormat = "hh:mm a";

public static String convertTimeFormat(String dateStr) {

    if (dateStr.equals("")) {
        return "";
    }
    Log.d("date", dateStr + "---" + sourceFormat + "---" + targetFormat);
    SimpleDateFormat form = new SimpleDateFormat(sourceFormat);
    Date date = null;
    try {
        date = form.parse(dateStr);
    } catch (Exception e) {
        e.printStackTrace();
    }
    SimpleDateFormat postFormater = new SimpleDateFormat(targetFormat);
    String newDateStr = postFormater.format(date);
    Log.d("Lead Response", newDateStr);
    return newDateStr;
}

非常感谢您在这件事上的时间和帮助。

1 个答案:

答案 0 :(得分:2)

private static final String sourceFormat = "hh:mm:ss";

更改为

private static final String sourceFormat = "HH:mm:ss";

我在“我的IDE”中查看了它的工作

private static final String sourceFormat = "HH:mm:ss";
    private static final String targetFormat = "hh:mm a";

public static String convertTimeFormat(String dateStr)  {

        if (dateStr.equals("")) {
            return "";
        }
        Log.d("date", dateStr + "---" + sourceFormat + "---" + targetFormat);

        **SimpleDateFormat form = new SimpleDateFormat(sourceFormat, Locale.US);**


        Date date = null;
        try {
            date = form.parse(dateStr);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        **SimpleDateFormat postFormater = new SimpleDateFormat(targetFormat, Locale.US);**

        String newDateStr = postFormater.format(date);
       Log.d("Lead Response", newDateStr);
        return newDateStr;
    }