当前位置: 首页 > 知识库问答 >
问题:

我需要将时间 24 小时格式显示为 12(上午/下午)小时格式 [重复]

鲜于华容
2023-03-14

在此代码中,在 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个答案

白修谨
2023-03-14
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;
    }
 类似资料:
  • 问题内容: 在我的应用程序中,我想将给定的CDT格式的24小时字符串转换为CDT格式的12小时的字符串,如何将给定的24小时格式的字符串转换为12小时的格式的字符串? 问题答案: 您可以尝试使用对象转换时间格式。 这是SimpleDateFromat 的javadoc 链接。

  • 问题内容: 我是Joda api的新手,我有这样的电话: 它打印为:。 希望我可以这样显示:。 我该如何实现? 提前致谢 问题答案: 请尝试以下操作:

  • 我正在使用TextView设置日期和时间与日期名称,但时间显示在24小时,我想设置在12小时格式。

  • 问题内容: sql server 2000表之一中具有以下格式的日期值 如何将上述格式的数据值转换为24小时日期格式,如下所示 问题答案: 试试这个: 首先将日期转换为,然后您可以按以下方式进行操作:

  • 问题内容: 我从服务器获得的时间就像 。 我想将其转换为。 我还希望转换后的时间为24小时格式。任何人都可以解决这个问题。我想得到的输出就像 问题答案: 试试这个:

  • 我有一个GMT时间格式,我通过使用以下方式将其更改为我的本地浏览器时间: 输出为: 现在我想在中将12小时格式更改为24小时格式 示例: 有什么建议吗? 谢谢

  • 问题内容: 我如何格式化大于24小时的timedelta以在Python中仅包含小时显示? 我通过以下方式达到目标: 有没有更好的办法? 问题答案: 可能定义继承的类会更加优雅

  • 问题内容: 如何在SQL Server 2008中将小时格式的时间转换为小时格式的时间? 问题答案: 当前时间是否在类型为time的变量/列中?如果是这样,这很容易: 结果: 如果在变量中,则必须在运行CONVERT之后删除日期部分。如果在字符串中,请先将其添加到中,然后使用上面的代码。