The dd
in your format string means that there are two digits representing the value of days. In your string, you dropped the leading 0
, so the day value is now only a single digit. The correct format string would therefore be dMMyy
, which would give you the correct date.
The better solution would be to make sure you're not losing the leading 0
though, by not treating the date as an integer, or by pre-padding the number with leading zeroes.
Anyway, quick solution in this case would be this:
String strDate = "0" + String.valueOf(70311);
Date date = new SimpleDateFormat("ddMMyy").parse(strDate);
Or
String strDate = String.valueOf(70311);
Date date = new SimpleDateFormat("dMMyy").parse(strDate);
See the SimpleDateFormat
documentation for more details.
Edit
A more reliable way of getting a String in the correct format (padded with 0
s on the left side) is to use String.format
, like this:
String.format("%06d", num);
As pointed out in the comments, this ensures that the 0
is added only in cases when it's needed:
String strDate = String.format("%06d", 70311);
Date date = new SimpleDateFormat("ddMMyy").parse(strDate);