Java SimpleDateFormat将“ 04:50 PM”转换为“ 16:50”

问题描述

我有一个关于从上午12点/小时格式转换为24小时格式的问题。我曾尝试过使用SimpleDateFormat,但遇到了一些问题。

enter image description here

如您所见,我打印了5行原始时间和转换时间,但是对于以“ PM”结尾的情况却失败了。请注意,某些输入为24小时格式,而其他输入则为12小时上午/下午格式。

下面是我为转换编写的代码

static String standardizeTime(String inputTime) throws ParseException {
        SimpleDateFormat[] testInputFormat = new SimpleDateFormat[2];

        SimpleDateFormat returnFormat = new SimpleDateFormat("HH:mm");
        testInputFormat[0] = new SimpleDateFormat("hh:mm aa");
        testInputFormat[1] = new SimpleDateFormat("HH:mm");
        
        testInputFormat[0].setLenient(false);
        testInputFormat[1].setLenient(false);

        Date time;
        for (int i = 0; i < testInputFormat.length; i++) {
            try {
                time = testInputFormat[i].parse(inputTime);
                return returnFormat.format(time);
            } catch (ParseException e) {
                continue;
            }
        }

        return "";
    }

解决此问题,我应该更改什么?

解决方法

这按预期工作。

import java.text.SimpleDateFormat;

public class HelloWorld{

     public static void main(String []args) throws Exception {
         final SimpleDateFormat parser = new SimpleDateFormat("hh:mm aa");
         final SimpleDateFormat printer = new SimpleDateFormat("HH:mm");
        System.out.println(printer.format(parser.parse("4:07 pm")));
     }
}

您的代码看起来不错,所以我认为问题出在其他地方。

,

我通过参考以下帖子解决了我的问题:java.text.ParseException: Unparseable date

问题是,我的计算机的默认语言不是英语,因此以Alexander的响应为例。我需要写:

id1 = int(input("Enter 4-digit account pin: "))
id2 = int(input("Re-Enter 4-digit account pin for confirmation: "))
while id1 != id2:
    id2 = int(input("Incorrect pin.. Please Re-enter: "))
id = id1

请注意解析器中的“ Locale.ENGLISH”!

,

每当日期/时间包含字母时,请确保将Locale与日期/时间格式API一起使用,因为不同的语言环境具有不同的字母表示形式。

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class Main {
    public static void main(String[] args) throws ParseException {
        DateFormat stfInput = new SimpleDateFormat("h:m a",Locale.ENGLISH);// 12-hour format
        DateFormat stfOutput = new SimpleDateFormat("HH:mm",Locale.ENGLISH);// 24-hour format
        Date time = stfInput.parse("02:57 AM");
        System.out.println(stfOutput.format(time));
        time = stfInput.parse("07:05 PM");
        System.out.println(stfOutput.format(time));
    }
}

输出:

02:57
19:05

注意java.util日期时间类已过时且容易出错,其格式API SimpleDateFormat也是如此。我建议您应该完全停止使用它们,并切换到modern date-time API。在 Trail: Date Time 上了解有关现代日期时间API的更多信息。

如果您正在为自己的Android项目执行此操作,并且您的Android API级别仍不符合Java-8,请选中Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project

使用现代的日期时间API:

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("h:m a",Locale.ENGLISH);// 12-hour format
        DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("HH:mm",Locale.ENGLISH);// 24-hour format
        LocalTime time = LocalTime.parse("02:57 AM",dtfInput);
        System.out.println(time.format(dtfOutput));
        time = LocalTime.parse("07:05 PM",dtfInput);
        System.out.println(time.format(dtfOutput));
    }
}

输出:

02:57
19:05
,

要解决此问题,我应该更改什么?

首先也是最重要的一点:我建议您使用java.time(现代的Java日期和时间API)进行时间工作。您尝试使用的日期时间类SimpleDateFormatDate的设计很差,而且已经过时了。现代的API更好用。 Arvind Kumar Avinash的答案的后半部分向您展示了方法。我没有理由重复它。是的,Arvind的代码可以解决您的问题。

您的代码出了什么问题?

有人说您的问题不是为格式化程序提供英语区域设置。这是事实的一部分,但并不能完全解释为什么07:05 PM被转换为07:05的情况下正确的转换会得到19:05

发生的事情是,您的第一个输入格式化程序,即模式为hh:mm aa的输入格式化程序,由于使用PM被称为其他语言的语言而无法解析。接下来是第二个格式化程序,在解析字符串时使用模式HH:mm 成功。令人惊讶,不是吗?我认为它不一定解析整个字符串,这是SimpleDateFormat的众多令人困惑的特征之一。它将07:05部分解析为一天中的小时 和分钟。然后,它忽略了字符串的其余部分。这样,您得到的结果07:05是错误的,而不是正确的19:05。这只是根本不使用SimpleDateFormat的原因之一。

链接