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

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

问题描述

在我的应用程序中,我正在以字符串格式从用户读取 date 参数。

In My Application I am reading the date parameter from user in the String format.

读取参数后,我需要转换 * 所需日期格式的字符串 *

After reading the parameter, I need to convert the String to *desired date format.*

所需格式= YYYY-MM-DD HH :MM:SS

输入字符串可以是任何格式。

Input String can be in any format.

例如:2013 / 09/19 14:21:07 OR 2013-09-19 14:21:07

Eg: 2013/09/19 14:21:07 OR 2013-09-19 14:21:07

无论获取的格式如何,我都需要将其转换为所需的格式。
如何实现?

Irrespective of the format Obtained, I need to convert it to desired format. How to achieve this?

我在其中看不到任何摘录,

I saw few snippet where,

SimpleDateFormat formatter = new SimpleDateFormat("YYYY/MM/DD HH:MM:SS"); 
Date dt = formatter.parse("2013/09/19 14:21:07");
SimpleDateFormat desiredFormatter = new
SimpleDateFormat("YYYY-MM-DD HH:MM:SS");

desiredFormatter .format(dt);

以上代码段仅在我们知道用于解析String的输入格式时才有效。
但是在我的情况下,我不知道输入格式。因此,我正在考虑直接使用 format 方法而不进行分析。

The above snippet works only when we know the input format to parse the String. But In my case I dont know the input format. So I was thinking to use directly format method without parsing.

这可能吗?

推荐答案

这是不可能的。您不能确定01/01/2013是 MM / dd / yyyy 还是 dd / MM / yyyy 事先知道真实格式

It's not possible. You cannot determine if 01/01/2013 is MM/dd/yyyy or dd/MM/yyyy if you dont know the real format beforehand

这篇关于如何在不知道字符串格式的情况下将字符串转换为日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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