Question

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

Was it helpful?

Solution 2

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.

OTHER TIPS

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:

  • before format: Shows the DEFAULT format for a Date that System.out.println offers.
  • after format: Shows the format given after using the SimpleDateFormat.
  • after parse: We are again in the first case.
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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top