1

我将日期和时间存储在字符串中,即我的字符串包含 str =“18/01/2013 5:00:00 pm”。如何在 android 中将其转换为 24 格式时间?

4

5 回答 5

2

您可以使用两个 SimpleDateFormat 实例:一个将输入解析为日期,另一个将日期格式化为具有所需格式的字符串。

例如,formattedDate在下面的代码中将是18/01/2013 17:00:00

String str = "18/01/2013 5:00:00 pm";
SimpleDateFormat input = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
Date dt = input.parse(str);

SimpleDateFormat output = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String formattedDate = output.format(dt); //contains 18/01/2013 17:00:00

笔记:

  • hh用于上午/下午 (1-12)HH中的小时,而用于白天 (0-23) 中的小时。
  • 有关更多格式选项,请查看javadoc
于 2013-01-18T12:18:28.130 回答
1

要获取 AM PM 和 12 小时日期格式,请使用hh:mm:ss a字符串格式化程序 WHEREhh 用于 12 小时格式,a用于 AM PM 格式。

注意: HH 是24小时,hh 是12小时日期格式

SimpleDateFormat formatter = new SimpleDateFormat("mm/dd/yyyy hh:mm:ss a");
            String newFormat = formatter.format(testDate);

例子

String date = "18/01/2013 5:00:00 pm";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/mm/dd HH:MM:SS");
        Date testDate = null;
        try {
            testDate = sdf.parse(date);
        }catch(Exception ex){
            ex.printStackTrace();
        }
        SimpleDateFormat formatter = new SimpleDateFormat("mm/dd/yyyy hh:mm:ss a");
        String newFormat = formatter.format(testDate);
        System.out.println(".....Date..."+newFormat);
于 2013-01-18T12:24:15.790 回答
1

尝试

    String str ="18/01/2013 5:00:00 pm";
    Date date = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a").parse(str);
    str = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(date);
    System.out.println(str);

输出

18/01/2013 17:00:00
于 2013-01-18T12:22:15.017 回答
0

您可以为此使用 SimpleDateFormat:

SimpleDateFormat dateFormat = new SimpleDateFormat(dd/mm/yyyy HH:mm:ss");

请参阅与您的要求相反的this 。刚刚发布了链接,以便您了解 HH 和 hh 的不同之处。

于 2013-01-18T12:18:11.490 回答
0

尝试使用 java SimpleDateFormat 类。

例子:

SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
df.parse(date);

大写 HH 使用 24h 格式

于 2013-01-18T12:18:58.327 回答