Convert String to Date Issue (Date Parsing) in JAVA
I am trying to convert a String like "05/30/2012" to a Date as same like "05/30/2012" and I'm using these codes.
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); Date d1=formatter.parse("05/30/2012"); System.out.println(d1);
But these codes compile result is : "Wed May 30 00:00:00 EEST 2012" I need "05/30/2012".
Note: I'm trying to convert String to Date. I have a Date column in Database. I don't want to change it's format. I just want 05/30/2012 in my database but as a Date class not a String. parse() method is changing my date to another format I want to keep it's format
I've solved it.
java.sql.Date dd = new java.sql.Date(formatter.parse("05/30/2012").getTime()); System.out.println(dd);
and now its result is : 05/30/2012
You need to use format() method then
By the way what is the point of conversion here if you already have string formatted?
if you just say System.out.println(dateinstance); then it will invoke toString() method of Date class which has fixed format,
So if you just want the conversion from String to Date then you can do it using parse() method,
If you want formatted conversion from Date to String then you need to use format() method
Just as you need to specify the format when parsing the date, you also need to specify the format when printing it, otherwise you get the default format that you are seeing.
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); Date d1=formatter.parse("05/30/2012"); String out = formatter.format(date); System.out.println(out);
The parse method will build a Date from a String with the given pattern, but your System.out.println(d1); will just call a Date.toString().
To print the Date with a custom format, you should use SimpleDateFormatter.format that will return the String as you want
There is nothing wrong with your code. The date is parsed, and in the System.out.println() call, the default implementation of Date.toString() is used. Note: the date doesn't know the format used for parsing
To "fix" it, i.e. do what you want, write