android - 将 12 (PM/AM)Hour AM PM 时间中的字符串转换为 24 小时时间 android

标签 android datetime time 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();
}

出现错误:

Method threw 'java.text.ParseException' exception.)

详细的错误信息是:

Unparseable date: "3:30 PM" (at offset 5)

但是如果我将 PM 替换为 p.m. 它可以正常工作,如下所示:

 timeComeFromServer = timeComeFromServer.replaceAll("PM", "p.m.").replaceAll("AM", "a.m.");

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

最佳答案

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));

输出是:

p.m.
PM

要不依赖于此,您可以在格式化程序中使用 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)));

输出是:

15:30

第二个格式化程序不需要特定的语言环境,因为它不处理特定于语言环境的信息。


Java 新日期/时间 API

旧类(DateCalendarSimpleDateFormat)有lots of problemsdesign issues ,并且它们正在被新的 API 取代。

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

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

您可以使用 org.threeten.bp.format.DateTimeFormatter 并将输入解析为 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));

输出是:

15:30

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

关于android - 将 12 (PM/AM)Hour AM PM 时间中的字符串转换为 24 小时时间 android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45661194/

相关文章:

Android 如何从我的应用程序使用 SD 卡中的文件路径预览图像

android - 如何在特定日期和时间在 android 中设置时区?

swift - 我怎样才能始终如一地获取 swift4 中两个日期之间所有天数的计数或列表?

date - 在本地时区获取 Haskell 中的日期

c# - 在 MVC 4 中保持和执行时间

android - Android 中上下文菜单的项目分隔符

java - 如何像在 Cocos2d 中那样在 Libgdx 中将子图像添加到 Sprite 中?

Android Intent 打开用户的首选浏览器

java - 将小时和分钟转换为毫秒并返回 HH :mm:ss Format

c - 当我第二次运行该程序时,它没有给我正确的执行时间