String selectedDate = \"2012-\" + createdMonth + \"-\" + createdDay;
SimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd\");
try {
createdDate = dateFo
You seem to think that createdDate
, which is a Date
object, has the format yyyy-MM-dd
. It doesn't. Date
objects don't have a format - they just contain a timestamp, just like numbers are just numbers, which don't have a format by themselves.
A SimpleDateFormat
object is used to parse a String
into a Date
object, or format a Date
object into a String
.
If you have a Date
object and you want to display the date in a particular format, then convert it to a String
with the appropriate format using a SimpleDateFormat
object:
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
String text = fmt.format(createdDate);
System.out.println("Created: " + text);
If you print a Date
object without explicitly formatting it, it will be formatted using a default format, which is why you see Thu Mar 08 00:00:00 CST 2012
.
A Date
object does not somehow remember what the format was of the String
that you parsed it from.
The parse
method returns a java.util.Date
and that is the what the Date
implementation of toString()
returns.
You need to print as below. Point is that you need to use the formatter object you have created while printing as well.
System.out.println(dateFormat.format(createdDate));
use dateFormat.format(createdDate)