Reputation: 361
I'm trying to format a Date object and convert that formatted one back to Date type object
This is my code
SimpleDateFormat inputDf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss zzz");
System.out.println("before format "+invoiceDate);
invoiceDate=inputDf.parse(inputDf.format(invoiceDate));
System.out.println("after format "+inputDf.format(invoiceDate));
System.out.println("after parse "+invoiceDate);
Out put from above code is
before format : Mon Jan 14 10:55:40 IST 2013
after format : Mon Jan 14 2013 10:55:40 IST
after parse : Mon Jan 14 10:55:40 IST 2013
You can see here after i parse the date object it converting back to original format(format which shows before format) but i want Date object like it appear in second print line(after format) thing is .format method returns String not a Date object, how can i fix this ?
Thanks
Upvotes: 1
Views: 1255
Reputation: 2434
The Date
object doesn't define any format. Date
is just a long number with time in it.
In order to modify its format you have to use a String
object, as you did in your example.
If you analyze your example:
Date
that System.out.println
offers.SimpleDateFormat
.Upvotes: 6
Reputation: 2327
This behaviour is because the SimpleDateFomat
does not impose itself upon the date. The SimpleDateFormat
is merely a pattern to get a formated output out of any Date
, but it does not change the date itself. Date
does not have a format, so
System.out.println("before format "+invoiceDate);
defaults to the default pattern format.
Actually, the SimpleDateFormat
is exactly the way to achieve what you want, ie use it to properly format your output everytime you need it. Formating a date object gives you a representation of it, a String
.
Upvotes: 1
Reputation: 49372
System.out.println("after parse "+invoiceDate);
Here you just trying to print the Date
object . The Date
object , per se, doesn't have any format. The class Date represents a specific instant in time, with millisecond precision. Hence we use DateFormat
to format the output string which is printed on printing the Date
object . To display the same output as second statement , you need to format it again.
System.out.println("after parse"+inputDf.format(invoiceDate));
Look at the Javadoc for implementation of the toString() for Date
:
Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy
Upvotes: 1