Kirmani88 Kirmani88 - 2 years ago 113
Java Question

SimpleDateFormat is not Formatting the Date as specified

I am trying to get current Date in the format. "yyyy/MM/dd". I have written following code to achieve this.

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd", Locale.US);
Calendar cal = Calendar.getInstance();

String dateStr = dateFormat.format(cal.getTime());
currentDate= dateFormat.parse(dateStr);

The value of current Date after process is this

Mon Jun 20 00:00:00 GMT+05:00 2016

The value of
after formatting is

Kindly guide me what i am doing wrong here.

Answer Source

You are confusing how it works.

DateFormat.format takes a Date and converts it to String. It is this string (dateStr in your code) that holds the date in the format you want.

DateFormat.parse takes a String and converts it to Date. The Date object is a date (more precissely a millisecond), it has no format. If you print the resulting Date object, it will be printed using its toString() implementation, which shows the Mon Jun... string. But that value is not related in any way to the DateFormat from which you generated the Date instance.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download