0

I need to parse the date as per format but it didn't work very well.

   public class Main {
        public static void main(String[] args) throws ParseException {
                DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
                String dateInString = "07/06/2013";
                Date date = formatter.parse(dateInString);
                System.out.println(date);
            }
        }

i need date object in 07/06/2013 format even if date was in any format. but parse method always return in Fri Jun 07 00:00:00 PKT 2013.

Cœur
  • 37,241
  • 25
  • 195
  • 267
T.Malik
  • 107
  • 1
  • 10
  • `Date` is nothing more then a container for the number of milliseconds since the unix epoch, it has no format of it's own, that's what `DateFormat` is for – MadProgrammer Apr 22 '15 at 07:49

1 Answers1

1

You can always have your date object in "dd/MM/yyyy" format - when you want to output it just use:

DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(formatter.format(date));

The reason you see Fri Jun 07 00:00:00 PKT 2013 displayed is because System.out.println uses the default toString representation of the object you provided. For Date instances it gives you such information (depending on locale, afaik).

P.S. keep in mind that instances of SimpleDateFormat are not thread-safe so it is better to create new ones.

Anton Sarov
  • 3,712
  • 3
  • 31
  • 48
  • then what is purpose of parse method in DateFormat? – T.Malik Apr 22 '15 at 07:58
  • You want to use objects as much as possible. In this case `Date` is a (very) good encapsulation for dates - with all their hours, minutes, timestamps and so on. Now imagine your application receives a date formatted as a `String`. You want to convert this to a `Date` object (with the parse method) so that you can manipulate it more easier! – Anton Sarov Apr 22 '15 at 08:00
  • Think of `parse` as an import and `format` as an export - everybody can deal with `String`s - that is why you "export" your date object and give it to them. Your users want to enter their birthday as a `String` in your application - this is where you "import" it so you can for example calculate how old they are – Anton Sarov Apr 22 '15 at 08:04
  • so that only way in parsing is by Locale specific formate – T.Malik Apr 22 '15 at 08:12