我有一个格式 MM/dd/yyyy
,所以所有格式都以个位数为前导零。问题是在解析时我希望能够同时解析 "11/25/2018"
和 "5/25/2018"
,但格式应始终返回前导零。
我试过使用不同的 ResolverStyle
选项,但没有成功。
构建我自己的特定格式似乎不合理,当你认为它是使用 SimpleDateFormat
开箱即用时。
如果有任何想法,不涉及使用 FormatterBuilder
从头开始制作格式化程序,我们将不胜感激
最佳答案
使用两种不同的格式,M/d/yyyy
用于解析,MM/dd/yyyy
用于打印。前者将接受一位数和两位数的月份和日期,而后者将始终打印两位数,必要时使用前导零。
SimpleDateFormat parseFormat = new SimpleDateFormat("M/d/yyyy");
SimpleDateFormat printFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date1 = parseFormat.parse("4/5/2010");
Date date2 = parseFormat.parse("04/05/2010");
String output1 = printFormat.format(date1);
String output2 = printFormat.format(date2);
// output1 and output2 will be the same
关于java - DateTimeFormatter 在解析个位数部分时过于严格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50579613/