Tutorial :Date format in jsp



Question:

I need to convert the date from request parameter to string in dateformat 'yyyy-MM-dd'.

I have tried the following

String MyDate = request.getParameter("DayCal");  formatdate = new java.text.SimpleDateFormat("yyyy/MM/dd");  Date date = (Date) formatdate.parse(MyDate);  String DisplayDate= formatdate.format(date);  

But i am getting incorrect results if the request.getParameter("DayCal") = 01/01/2010; the DisplayDate = 0006/07/03

Please help... Thanks in advance


Solution:1

You will need two SimpleDateFormats - one for parsing and one for formatting:

String MyDate = request.getParameter("DayCal");  SimpleDataFormat parseDate = new java.text.SimpleDateFormat("dd/MM/yyyy");  SimpleDataFormat formatDdate = new java.text.SimpleDateFormat("yyyy-MM-dd");  Date date = (Date) parseDate.parse(MyDate);  String DisplayDate= formatDate.format(date);  

(I added dashes instead of slashes, because that was your initial requirement).


Solution:2

From your code, request.getParameter() returns date as dd/MM/YYYY or mm/dd/yyyy, but your SimpleDateFormat() is given yyyy/MM/dd parameters which doesnot match MyDate. Instead SimpleDateFormat() should be given dd/mm/yyyy or mm/dd/yyyy.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »