Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert String to Date without knowing the format?

Tags:

java

date

format

I have a problem. I am trying to convert some strings to date, and I don't know the format the date is arriving.

It might come as yyyy.mm.dd hh:mm:ss or MM.dd.yy hh:mm:ss and so on.

How can I convert these strings to Date? I tried this:

DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); Date d = (Date)formatter.parse(someDate); 

But when I printed out someDate it printed out like this: 2010-08-05 12:42:48.638 CEST which means yyyy.mm.dd hh:mm:ss, however when I ran the above code, the date object now became Sat Jan 31 00:42:48 CET 11 which is strange to say the least.

Any ideas how I can correctly format strings to date?

like image 832
Shervin Asgari Avatar asked Sep 14 '10 09:09

Shervin Asgari


People also ask

How do I turn a string into a date?

Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.

Which function is used convert string into date format?

Date() Function. as. Date() function in R Language is used to convert a string into date format.

How do I format a string to mm dd yyyy?

string dateString = int. Parse("20120321"). ToString("yyyy/MM/dd");


1 Answers

You cant!

If you have the date 2010-08-05 then it can be either 5th August 2010, or 8th May 2010 - you need to know the date format (or at least prioritise one format over the over) to tell them apart.

like image 53
Justin Avatar answered Sep 25 '22 10:09

Justin