Monday, 20 March 2017

java.sql.Date (YYYY-MM-DD) to java.util.Date (DD-MMM-YYYY) conversion



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


Answer



This is because you re-parse the date once it has been formatted.



date = format1.parse(input);
String temp = format2.format(date);
Date outDate = format2.parse(temp);
System.out.println(outDate);



Simply do



date = format1.parse(input);
String temp = format2.format(date);
System.out.println(temp)


Note that if you have JSTL you can format direcytly in the page:




<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>






No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...