我怎么知道字符串的格式是否与输入值的格式相同?在 java

How can I know if the format of a string is the same as the format of an input value? in java

First, thanks, Elder Developer, I’m super newbie... and sorry I don't speak English well.... so.. understand my sentence..

我想知道比较a的格式和DateStringFormat的方式。

示例:

boolean CompareFormat(String inputValue, DateTimeFormatter format) {
    String gettedFormat = ~~~.getFormat(inputValue);
    if (format.toString().equals(gettedFormat)) return true;
    else return false;
}

只是,我觉得...

  1. 获取格式化的输入字符串值。
  2. 将格式化值更改为格式 (我认为,将值更改为再次格式化它不会改变 / 输入值:19900202T0001 -> 更改为格式 (yyyyMMddThhmm)-> 结果:19900202T0001)
  3. 如果输入值与更改为格式的值相同,则return为真;别的 假的;

但我得不到我想的结果。

我试过了

            System.out.println("format : " + format);
            System.out.println("value : "+value);
            LocalDate changedDateString = LocalDate.parse(value, formatter);
            System.out.println("changed Value : " + changedDateString);
            System.out.println("changed Value : " + formatter.format(changedDateString));

输出:

format : yyyyMMdd'T'hhmm
value : 20170616T0023
changed Value : 2017-06-16
18:19:14.053 ERROR ServiceTask - Exception caught.

我不确定你到底想得到什么,但我想我会提出一个建议。对于检查给定输入字符串是否与给定格式匹配的布尔方法,我认为简单的检查是尝试使用格式解析字符串并查看是否成功:

public static boolean compareFormat(String inputValue, DateTimeFormatter format) {
    try {
        format.parse(inputValue);
        // parsing succeeded; so the format seems to match
        return true;
    } catch (DateTimeParseException dtpe) {
        return false;
    }
}

像这样使用,例如:

    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd'T'hhmm");
    System.out.println(compareFormat("20170616T0023", dtf));

这会打印 true。另一方面,compareFormat("2017-06-16", dtf) 产生错误。

该方法不检查我在评论中提到的方面,输入看起来像 LocalDate(没有小时和分钟)还是 LocalDateTime(如示例中所示)或其他。

您问题中的代码示例抛出 java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: ClockHourOfAmPm,我想这就是 18:19:14.053 ERROR ServiceTask - Exception caught. 行的原因。这是因为您正在尝试使用包含 hhmm 的格式化程序来格式化 LocalDatehh 表示 clock-hour-of-am-pm (1-12),通常与 AM/PM 标记一起使用,如“9:15 AM”。无论如何,LocalDate 只包含日期,没有小时和分钟,所以它不能用你的 DateTimeFormatter.

格式化。