如何将字符串转换为日期而不知道格式? [英] How to convert String to Date without knowing the format?
问题描述
可能会以 yyyy的形式出现。 mm.dd hh:mm:ss
或 MM.dd.yy hh:mm:ss
等等。
如何将这些字符串转换为Date?
我试过这个:
DateFormat formatter = new SimpleDateFormat(dd-MM-yyyy hh:mm:ss );
日期d =(日期)formatter.parse(someDate);
但是当我打印出一些日期时,它打印出如下:2010-08-05 12:42: 48.638 CEST这意味着 yyyy.mm.dd hh:mm:ss
,但是当我运行上面的代码时,日期对象现在变成 Sat Jan 31 00:42:48 CET 11
这是至少说奇怪的。
任何想法如何正确格式化字符串到日期? p>
你不能!
如果你有日期 2010-08-05
那么它可以是2010年8月5日或2010年5月8日 - 你需要知道日期格式(或至少优先考虑一种格式把它们分开。
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?
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.
这篇关于如何将字符串转换为日期而不知道格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!