如何将字符串转换为日期而不知道格式? [英] How to convert String to Date without knowing the format?

查看:616
本文介绍了如何将字符串转换为日期而不知道格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题。我正在尝试将一些字符串转换为日期,我不知道日期到达的格式。



可能会以 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆