Vishal Hegde wrote:
Do you understand what that code is doing? Let's look at it line by line.
1. Gets a Date object from somewhere (probably a ResultSet, so it comes out of a database query). This Date object isn't used in the rest of the code, so it isn't relevant here.
2. Creates a SimpleDateFormat object with the format "yyyy-MM-dd".
3. Creates a new Date object set to the current date and time.
4. Formats the Date object from line 3 into a string, which will have the format "yyyy-MM-dd".
5. Parses that String into a Date object again.
6. Prints the Date object from line 5 using the default format that Date.toString() uses.
Many people are confused about Date objects, formatting and parsing, because a lot of people are asking questions about this on this and other websites.
Here are some important things to understand:
1.
Date objects do not have a format by themselves. You cannot "have a Date object in the format yyyy-MM-dd". Sometimes people are asking questions like "I want my Date object in the format XYZ. How can I do that?". The question is wrong, because Date objects don't know anything about formatting.
2. Converting a Date object to a String is called
formatting and converting a String to a Date object is called
parsing.
3. You
use a DateFormat object to format a Date or parse a String.
The DateFormat object is the only thing that knows the format.
4. When you parse a String into a Date object, the Date object does not remember anything about the String or the format that it was in. A Date is just a Date, just like a number is just a number; it does not have an inherent format.
5. When you print a Date object "directly" (by explicitly or implicitly calling toString on it, as you are doing in line 6 of your code), it is formatted using a default format that makes it look like "Thu Jun 27 00:00:00 IST 2013".
Something else to understand about Date objects:
A java.util.Date object contains a timestamp, a number of milliseconds since 01-01-1970, 00:00:00 GMT. You cannot store just a day-month-year in a Date object. It will always also contain a time.
If you have to work with dates and times, I strongly recommend using
Joda Time, a popular library with a much better API for dealing with dates and times than
Java's Date and Calendar classes. For example, if you need to store just a day-month-year, you'd use Joda Time's class LocalDate for that. In Java 8, there's going to be a new date and time API which will be based on Joda Time.