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

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

问题描述

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

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

它可能是 yyyy.mm.dd hh:mm:ssMM.dd.yy hh:mm:ss 等等.

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);

但是当我打印出 someDate 时它打印出来是这样的:2010-08-05 12:42:48.638 CEST 这意味着 yyyy.mm.dd hh:mm:ss,但是当我跑上面的代码,日期对象现在变成了 Sat Jan 31 00:42:48 CET 11 这至少可以说很奇怪.

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?

推荐答案

你不能!

如果您有日期 2010-08-05 那么它可以是 2010 年 8 月 5 日或 2010 年 5 月 8 日 - 您需要知道日期格式(或至少优先考虑一种格式)来区分它们.

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天全站免登陆