0

I am reading date values from a file in which i am reading it as string object.

The date values varies in many format for example sew below:

01-Mar-2012
01/12/2012
01-12-2012
01.12.2012
01.Mar.2012
07/01/2008 12:00:00
07/01/2008 12:00:00 AM

What ever be the format i want the date object in format dd/mm/yyyy.

There is so many combinations.

SimpleDateFormat expect me to provide the pattern to format it .

Is there is any way to guess the pattern or create a date object from the given string?

Wills
  • 491
  • 8
  • 20

2 Answers2

2

how can you know if 12-6-2012 is 6th december or 12th june?!

what you could do is defining an array with all possible patterns.

then try to parse the date for each array entry (if it throws an exceptionen try the nexct pattern and so on)

i know that this is a pretty ugly attempt but it works!

Philipp Sander
  • 10,139
  • 6
  • 45
  • 78
  • yup this is exactly is what i am having in my mind thought there would be another way around. you there is no simple method to convert a string to date without pattern any specific reason ? – Wills Apr 30 '13 at 14:40
  • 1
    not as far as i know. i described the main problem in the first row of my answer. – Philipp Sander Apr 30 '13 at 14:42
  • when "guessing" the pattern, you have to choose a priority. and thats what you do with the array – Philipp Sander Apr 30 '13 at 14:44
  • aah i totally agree with you didnt get that in first place let me get on writing it thanks – Wills Apr 30 '13 at 14:44
0

What ever be the format i want the date object in format dd/mm/yyyy.

A java.util.Date object does not have a format - the only information it contains is an instant in time (specifically, the number of milliseconds since 01-01-1970, 00:00:00 GMT).

So, you cannot have a "date object in format dd/mm/yyyy". Date objects don't have a format, just like numbers don't have an inherent format.

If you want to display the date in the format dd/mm/yyyy, then you have to convert it to a string first using a SimpleDateFormat object; you specify the format on the SimpleDateFormat object (not on the Date object itself).

// NOTE: use MM instead of mm; MM = months, mm = minutes
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");

Date now = new Date();

// Display the date in the format dd/MM/yyyy
System.out.println(df.format(now));
Jesper
  • 202,709
  • 46
  • 318
  • 350