我的格式为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