使用 SimpleDateFormat 问题将字符串转换为时间

Converting String to Time using SimpleDateFormat issues

因此,我使用 SimpleDateFormat 将 "HH:MM AA" 的字符串转换为 "HH:MM", 问题是我的代码在 eclipse 上运行良好,但是当我在 Android Studio 上 运行 时,它显示错误的输出。这是我的两个代码。

试试这个代码..

 String date="2:30 PM";
    SimpleDateFormat sdf5 = new SimpleDateFormat("hh:mm aa");
    SimpleDateFormat sdf6 = new SimpleDateFormat("HH:mm");
    try {
        String str=sdf6.format(sdf5.parse(date));
        Log.d("DATE TO:",str);
    } catch (ParseException e) {
        e.printStackTrace();
    }

问题是您使用 "MM" 作为分钟,但它应该是 "mm"。 "MM" 是几个月。

当您想要返回 24 小时值时,"HH" 部分很好。

尝试这样的事情:

public static String getTimeFormatted(String time){
    String s = "";
    try{
        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa", Locale.US);
        Date d = sdf.parse(time);


        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm", Locale.US);
        s = formatter.format(d);
    }
    catch(Exception ex){
        s = ex.getMessage();
    }
    return s;
}

试试这个

  public String changeDateFormatFromAnother(String date){
        @SuppressLint("SimpleDateFormat") DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        @SuppressLint("SimpleDateFormat") DateFormat outputFormat = new SimpleDateFormat("dd MMMM yyyy");
        String resultDate = "";
        try {
            resultDate=outputFormat.format(inputFormat.parse(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return resultDate;
    }

java.time

    String newTimeString = LocalTime
            .parse("2:30 PM", DateTimeFormatter.ofPattern("h:mm a", Locale.ENGLISH))
            .toString();
    System.out.println(newTimeString);

这会打印

14:30

即使在 Android 上,你也应该考虑不要与年老且臭名昭著的麻烦 SimpleDateFormat class 打架。 java.time,现代 Java 日期和时间 API,更易于使用。 LocalTime 是一天中没有日期和时区的时间,所以看起来非常符合您的要求。

问题:我可以在 Android 上使用 java.time 吗?

是的,java.time 在新旧 Android 设备上都能很好地工作。只需要至少 Java 6.

  • 在 Java 8 和更高版本以及较新的 Android 设备上(据我所知,来自 API 级别 26)现代 API 是内置的。
  • 在 Java 6 和 7 中获取 ThreeTen Backport,新 classes 的 backport(ThreeTen 用于 JSR 310;请参阅底部的链接)。
  • 在(较旧的)Android 使用 ThreeTen Backport 的 Android 版本。它叫做 ThreeTenABP。并确保使用子包从 org.threeten.bp 导入日期和时间 classes。

你的代码出了什么问题?

  • 在您的第一个屏幕截图中,您正在使用格式模式进行格式化 字符串 HH:mm。大写 HH 表示一天中的小时,小写 mm 表示 小时的分钟。所以你得到了预期的 14:30.
  • 在您的第二个屏幕截图中,您使用了 HH:MM,即大写 MM。这是一个月。由于您解析的字符串中没有月份,因此默认为 January,而 January 在您的结果中又呈现为 01,因此您得到了 14:01SimpleDateFormat 非常典型,它同意打印一个从未出现过的月份,只是假装一切正常,不会通知您错误。这只是我建议您避免 class.
  • 的众多原因之一

链接