You are using the wrong input given the format of SimpleDateFormat
, which should be of form 11/09/2021
(note that month comes before day):
String dateFormat = "11/09/2021";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date strtDt = sdf.parse(dateFormat);
String strt = sdf.format(strtDt);
Otherwise, you can change the date pattern when constructing the SimpleDateFormat
:
String dateFormat = "20211109";
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date strtDt = sdf.parse(dateFormat);
String strt = sdf.format(strtDt);
EDIT
You can switch between formatter according to your input formatted string using a regular expression pattern matching:
Pattern pattern = Pattern.compile("^\\d{8}$");
SimpleDateFormat sdf;
if (pattern.matcher(input).matches()) {
sdf = new SimpleDateFormat("yyyyMMdd");
} else {
sdf = new SimpleDateFormat("MM/dd/yyyy");
}
Date strtDt = sdf.parse(input);
String strt = sdf.format(strtDt);
You can also catch the ParseException
to attempt another format parsing but I wouldn't recommend using exceptions for your program flow.
As @Ole V.V. suggested in his comment, you shouldn't be using the java.text.SimplateDateFormat
and the java.util.Date
classes for date types manipulation and parsing as those are outdated and may cause a lot of trouble along the way.
If you are on JDK 1.8 and onward, you should use the new Date Time APIs introduced in JSR 310:
String dateFormat = "20211109";
DateTimeFormatter formatter = DateTimeFormatter.BASIC_ISO_DATE;
// Same as `DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");`
LocalDateTime strtDt = formatter.parse(dateFormat, LocalDateTime::from);
String strt = formatter.format(strtDt);