Need advise how to send the java.sql.Date (YYYY-MM-DD) to java.util.Date (DD-MMM-YYYY).
The class java.sql.Date is designed to carry only a date. I have a table with column EXPIRY_DATE as DATE data type.
When I do the following
rs.getDate("EXPIRY_DATE")
it gives the output in the format YYYY-MM-DD. For example, 2015-04-05
I have a following Java bean
class ABC {
java.util.Date expiryDate;
}
I want to return the above bean as it is to the JSP page view as JSON object. As we are using Spring REST Controller (@RestController Service), I wrote the following line,
@RestController
@RequestMapping("/url")
class someClass {
@RequestMapping("/url")
Object someWebServiceMethod() {
ABC object = new ABC();
object.setExpiryDate( resultSet.getDate("EXPIRY_DATE") );
return object;
}
}
My webservice returns the date as it is in java.sql.Date format like YYYY-MM-DD.
I want to send the output in DD-MMM-YYYY format to the JSP page view.
How to convert the same?
I have tried the following code,
NOTE: The below code is irrelevant to my above question. I need solution only for the above @RestController spring code
public static void convertDate() {
String input = "2013-09-14";
// DateFormat format = DateFormat.getInstance();
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-mm-dd");
SimpleDateFormat format2 = new SimpleDateFormat("dd-MMM-yy");
Date date;
try {
date = format1.parse(input);
String temp = format2.format(date);
Date outDate = format2.parse(temp);
System.out.println(outDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
But it gives the output as Mon Jan 14 00:00:00 IST 2013
I want to send the date, in the format dd-MMM-YYYY like 28-Feb-2015
Presently My @RestController code returns the java.sql.Date format like 2015-02-28. But I want to be 28-Feb-2015.
Please advise how to do java.sql.Date (YYYY-MM-DD) to java.util.Date (DD-MMM-YYYY) conversion
Thanks
I want to send the output in DD-MMM-YYYY format to the JSP page view.
Then you need to use a SimpleDateFormat
to do so. Currently you're using the result of Date.toString()
, and ignoring temp
which should already have the right result.
However, you shouldn't need to parse the java.sql.Date
at all - you can just pass it straight to DateFormat.format
:
java.sql.Date date = /* get date from database */;
// TODO: Specify time zone and locale
SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = format.format(date);
Alternatively, I suspect that JSP already has a mechanism for allowing you to pass the date straight to the JSP itself, and specify the output format there... this is really a conversion to move as close to the presentation layer as possible.
See more on this question at Stackoverflow