0

How can we get the format of a date in Java?? I have a column which is in the date format . I want to find its format for every rows. How can i do this ? Ex --

COL1| COL2          |COL3
-------------------------
1   | 12-2005-31    |zzz
2   | 24 March 2009 |aaa
Harry Joy
  • 58,650
  • 30
  • 162
  • 207
justin3250
  • 303
  • 3
  • 10
  • 19
  • 3
    How would you distinguish between a numerical month and a day of month <= 12? – Alistair A. Israel Nov 11 '11 at 08:49
  • 1
    some date formats are ambiguous. 10-11-12 could be 2010 Nov 12 or 10 Nov 2012 or Oct 11, 2012. – Peter Lawrey Nov 11 '11 at 08:52
  • why do you have different formats in the same column? it is not safe to interpret date formats through code. I would suggest that you fix the formats in the column/ source. – aishwarya Nov 11 '11 at 09:07
  • ok convert the date to string using dateValue.toString() . Once we get it in string check dis discussion http://stackoverflow.com/questions/8008000/string-to-date-with-no-format-specified – justin3250 Nov 11 '11 at 09:22

4 Answers4

1

As per this SO answer, Generic way to parse dates in Java, there is no way to this. There are some partial solutions, but nothing definitive.

Community
  • 1
  • 1
Pieter
  • 3,339
  • 5
  • 30
  • 63
1

Looks like you are storing date as strings in your database. I suggest you change the column type to Date or Timestamp in the database table and save yourself from parsing horrors.

Manish
  • 3,913
  • 2
  • 29
  • 45
1

You cannot simply parse a string to form a Date because of the obvious ambiguity associated with the interpretation of the date string. For example, consider the date presented as "10/12/2009". One can interpret it as 10th of December and also as 12th of October. You can not map this string to a definitive date value unless you know the pattern it conforms to.

I agree with @Manish Sharma that changing the column type to Date would be a solution to your problem because Date values are stored as absolute seconds value starting from some fixed date in the past.

Drona
  • 6,886
  • 1
  • 29
  • 35
0

You will have to do your own heuristic or simply said "guess". Create a list of regexp Patterns and use the first that matches to construct a Date instance. Hope that your date's formats in database are not too variable.

Rostislav Matl
  • 4,294
  • 4
  • 29
  • 53