DateTimeFormatter is being too strict on parsing single-digit parts

  • A+
Category:Languages

I have a format MM/dd/yyyy, so everything formatted is with leading ZERO on single digit. The problem is that on parsing I want to be able to parse both "11/25/2018" and "5/25/2018", but formatting should always return leading zeros.

I've tried using different ResolverStyle options without any luck.

Building my own specific format seems unreasonable, when you think, that it was working out of the box using SimpleDateFormat.

Would appreciate any idea, that does not involve making formatter from scratch using FormatterBuilder

 


Use two different formats, M/d/yyyy for parsing, and MM/dd/yyyy for printing. The former will accept both single and double digit months and days, while the latter will always print double-digits, with leading zero if necessary.

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 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: