将字符串在12(PM/AM)小时AM PM时间转换为24小时时间android

ahm*_*mad 5 time datetime android datetime-parsing

我有来自服务器的转换时间的问题,我想将其转换为24小时.我正在使用以下代码:

String timeComeFromServer = "3:30 PM";

SimpleDateFormat date12Format = new SimpleDateFormat("hh:mm a");

SimpleDateFormat date24Format = new SimpleDateFormat("HH:mm");
try {
    ((TextView)findViewById(R.id.ahmad)).setText(date24Format.format(date12Format.parse(timeComeFromServer)));
} catch (ParseException e) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

有错误:

方法抛出'java.text.ParseException'异常.)

详细的错误消息是:

无法解释的日期:"下午3:30"(偏移5)

但是,如果我更换PMp.m.它的工作原理没有任何这样的问题:

 timeComeFromServer = timeComeFromServer.replaceAll("PM", "p.m.").replaceAll("AM", "a.m.");
Run Code Online (Sandbox Code Playgroud)

谁能告诉我哪种方法正确?

小智 1

SimpleDateFormat使用系统的默认区域设置(您可以使用java.util.Locale类调用来检查Locale.getDefault())。该区域设置是特定于设备/环境的,因此您无法控制它,并且在每个设备中可能会产生不同的结果。

某些区域设置的 AM/PM 字段可能具有不同的格式。例子:

Date d = new Date();
System.out.println(new SimpleDateFormat("a", new Locale("es", "US")).format(d));
System.out.println(new SimpleDateFormat("a", Locale.ENGLISH).format(d));
Run Code Online (Sandbox Code Playgroud)

输出是:

下午
下午

为了不依赖于此,您可以Locale.ENGLISH在格式化程序中使用,这样您就不会依赖系统/设备的默认配置:

String timeComeFromServer = "3:30 PM";
// use English Locale
SimpleDateFormat date12Format = new SimpleDateFormat("hh:mm a", Locale.ENGLISH);
SimpleDateFormat date24Format = new SimpleDateFormat("HH:mm");
System.out.println(date24Format.format(date12Format.parse(timeComeFromServer)));
Run Code Online (Sandbox Code Playgroud)

输出是:

15:30

第二个格式化程序不需要特定的区域设置,因为它不处理特定于区域设置的信息。


Java 新的日期/时间 API

旧的类(DateCalendarSimpleDateFormat)有很多问题设计问题,它们正在被新的 API 所取代。

一个细节是它SimpleDateFormat始终适用于Date具有完整时间戳(自 以来的毫秒数)的对象,并且两个类都隐式地在幕后1970-01-01T00:00Z使用系统默认时区,这可能会误导您并生成意外且难以调试的结果。但在这种特定情况下,您只需要时间字段(小时和分钟),无需使用时间戳值。新的 API 针对每种情况都有特定的类,更好且更不容易出错。

在 Android 中,您可以使用ThreeTen Backport,它是 Java 8 新日期/时间类的一个很好的向后移植。为了使其工作,您还需要ThreeTenABP(更多关于如何使用它的信息,请参见此处)。

您可以使用 aorg.threeten.bp.format.DateTimeFormatter并将输入解析为 a org.threeten.bp.LocalTime

String timeComeFromServer = "3:30 PM";

DateTimeFormatter parser = DateTimeFormatter.ofPattern("h:mm a", Locale.ENGLISH);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");

LocalTime time = LocalTime.parse(timeComeFromServer, parser);
System.out.println(time.format(formatter));
Run Code Online (Sandbox Code Playgroud)

输出是:

15:30

对于这种特定情况,您也可以使用它time.toString()来获得相同的结果。您可以参考javadoc了解有关向后移植 API 的更多信息。