How to convert the Date format and store it in a Date field(not in string or println) with the new format in Java

I'm trying to get the date from an object and changing the format and down the line I need to use the date value as a date field itself(not as string).

The format is getting changed by using format() method of SimpleDateFormat. But the default format is getting used when we assign this string value back to the date field by using parse() method of SimpleDateFormat. Uses Spring MVC and need to pass this date-MM/dd/yyyy to the JSP file as a model attribute.

PFB code and the comments for the date format generated after processing that line.

Date date1 = student.getDateOfBirth();        // Tue May 16 00:00:00 IST 2017
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
String dateStr = dateFormat.format(date1);    // 05/16/2017
Date date2 = format.parse(dateStr);           // Tue May 16 00:00:00 IST 2017
student.setDateOfBirth(date2);
Jon Skeet
people
quotationmark

A Date object doesn't have any state representing a format. It's just an instant in time. If you've got the right value in date1, then formatting and parsing it is completely pointless.

Instead, when you want the Date in a particular format later on, you should format it there. (Note that you should decide which time zone you're interested in, too.)

people

See more on this question at Stackoverflow