I am having issue with formatting strings to dates to the format 'dd-MMM-yy'. Would anyone have any idea why its parsing strings to full format rather than 'dd-MMM-yy'.
String =
["01-Dec-20","02-Dec-20","03-Dec-20","04-Dec-20","05-Dec-20","06-Dec-20","07-Dec-20","08-Dec-20","09-Dec-20","10-Dec-20","11-Dec-20","12-Dec-20","13-Dec-20","14-Dec-20","15-Dec-20","16-Dec-20","17-Dec-20","18-Dec-20","19-Dec-20","20-Dec-20","21-Dec-20","22-Dec-20","23-Dec-20","24-Dec-20","25-Dec-20","26-Dec-20","27-Dec-20","28-Dec-20","29-Dec-20","30-Dec-20","31-Dec-20"]
For date in the string I want to convert to Date with format 'dd-MMM-yy'
String dates = dateType.replace("\"", "").replace("[", "").replace("]", "");
List<String> stringList = new ArrayList<String>(Arrays.asList(dates.split(",")));
ArrayList<Date> dateList = new ArrayList<Date>();
stringList.forEach(d -> {
try {
Date date = new SimpleDateFormat("dd-MMM-yy").parse(d);
dateList.add(date);
} catch (ParseException e) {
e.printStackTrace();
}
});
The date list converts the strings to :
[Tue Dec 01 00:00:00 UTC 2020, Wed Dec 02 00:00:00 UTC 2020, Thu Dec 03 00:00:00 UTC 2020, Fri Dec 04 00:00:00 UTC 2020, Sat Dec 05 00:00:00 UTC 2020... etc ```
Dateobject, it looks like that "full format", and not a different, arbitrary format. If you want to those dates to look likedd-MMM-yy, you have to use the formatter and convert them to strings in that format. ADateitself is not associated with any particular format.setDate? It's been a while since I last did jdbc, but either that or that plus converting the date to java.sql.Date should work without you needing to convert the date to string (unless your database column is char-typed and not date/timestamp-typed)SimpleDateFormatandDate. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead useLocalDateandDateTimeFormatter, both from java.time, the modern Java date and time API. For an SQL query pass yourLocalDateto one of thePreparedStatement.setObjectmethods (no need to worry about format).Dategoes for bothjava.util.Dateandjava.sql.Date(the latter being a hack on top of the former).