Reputation: 57
i am getting my date input as a string in the format dd-mm-yy
through jsp page. Because this format is better to understand . But now i want to store the date in yyyy-MM-dd HH:mm:ss
format in my database. I am using the following code.
try
{
String s="30-04-2013";
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
d1=new SimpleDateFormat("yyyy-MM-dd").parse(s);
System.out.println(d1);
System.out.println(ft.format(d1));
} catch(Exception e) {
System.out.println("Exception:"+e);
}
My Jsp date format is dd-mm-yy
, but it gives answer as
Tue Oct 04 00:00:00 IST 35
0035-10-04 00:00:00
what is my mistake? can tell me anyone please
Thank you.
Upvotes: 0
Views: 2937
Reputation: 997
See below the working program. See the parse and format method.
import java.text.SimpleDateFormat;
public class DateParsing {
public static void main(String args[]) {
String s = "30-04-2013";
SimpleDateFormat ft = new SimpleDateFormat("dd-MM-yyyy");
SimpleDateFormat nt = new SimpleDateFormat("yyyy-MM-dd");
try {
System.out.println(nt.format(ft.parse(s)));
}
catch (Exception e) {
System.out.println("Exception:" + e);
}
}
}
Upvotes: 0
Reputation: 230
i think you need to pass the Date object to format() method of SimpleDateFormat class instead of passing string to it
just try to do like as follows
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formatted_date = ft.format(new Date());
System.out.println(formatted_date);
let me know the status
happy coding
Upvotes: 0
Reputation: 1038
Change the format in your code from yyyy-MM-dd
to dd-MM-yyyy
. A simple debug would have solved this issue.
Upvotes: 0
Reputation: 45060
d1=new SimpleDateFormat("yyyy-MM-dd").parse(s);
should be
d1=new SimpleDateFormat("dd-MM-yyyy").parse(s);
because the input date String you've provided String s="30-04-2013";
is of the format, dd-MM-yyyy
. Hence, to parse this, you need to give dd-MM-yyyy
format in your SDF.
Upvotes: 1