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;
}
只是,我认为...
- 获取格式化输入字符串值。
- 将格式化值更改为格式 (我认为,更改值再次更改为格式它不会改变 /输入值:19900202T0001 -> 更改为格式 (yyyyMMddThhmm)-> 结果:19900202T0001)
- 如果输入值与更改格式的值相同,则返回 true;别的 假;
但我无法得到我认为的结果。
我试过了
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.
最佳答案
我不确定你到底想得到什么,但我想我应该提出一个建议。对于检查给定输入字符串是否与给定格式匹配的 boolean 方法,我认为简单的检查是尝试用格式解析字符串并查看是否成功:
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)
产生 false。
该方法不会检查我在评论中提到的方面,无论输入看起来像 LocalDate
(没有小时和分钟)还是 LocalDateTime
(如在示例中)或其他东西。
您问题中的代码示例抛出 java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: ClockHourOfAmPm
,我认为这是行 18:19:14.053 ERROR ServiceTask 的原因- 捕获异常。
。这是因为您尝试使用包含 hh
和 mm
的格式化程序来格式化 LocalDate
。 hh
表示上午下午 (1-12) 的时钟时间,通常与 AM/PM 标记一起使用,如“9:15 AM”。无论如何,LocalDate
仅包含日期,没有小时或分钟,因此无法使用 DateTimeFormatter
对其进行格式化。
关于java - 如何知道字符串的格式是否与输入值的格式相同?在java中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44585870/