在我的应用程序中我正在以字符串格式从用户那里读取 date 参数。
阅读参数后,我需要将字符串转换为 * 所需的日期格式 。 *
所需格式= YYYY-MM-DD HH:MM:SS
输入字符串可以是任何格式。
例如:2013/09/19 14:21:07 或 2013-09-19 14:21:07
无论获取的格式如何,我都需要将其转换为所需的格式。 怎么做到这一点?
我看到了几个片段,
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的输入格式时,上述代码段才有效。 但在我的情况下,我不知道输入格式。所以我想在没有解析的情况下直接使用格式方法。
这可能吗?
答案 0 :(得分:4)
这是不可能的。如果您事先不知道真实格式,则无法确定01/01/2013是MM/dd/yyyy
还是dd/MM/yyyy
答案 1 :(得分:0)
正如你所说,日期将是例如:2013/09/19 14:21:07或2013-09-19 14:21:07
我认为这种方式对你有用
String text="date in yyy/mm/dd or yyy-mm-dd"
SimpleDateFormat sdf1=null;
try {
if(text.contains("/"))
{
sdf1 = new SimpleDateFormat("yyyy/MM/dd");
}
else
{
sdf1 = new SimpleDateFormat("yyyy-MM-dd");
}
SimpleDateFormat sdf2 = new SimpleDateFormat("MMM dd yyyy");
Date date = sdf1.parse(text);
System.out.println("Result==> " + sdf2.format(date));
} catch (ParseException exp) {
exp.printStackTrace();
}
答案 2 :(得分:0)
谢谢你们, 对于你的所有评论和答案。
即使我觉得在不知道输入格式的情况下也无法将String转换为Date。 无论如何,我会尝试重新设计,以改变读取输入的方式。
再次感谢。
答案 3 :(得分:0)
这取决于设计。
1. If user can type any format in GUI side, then we can't able to convert, simply its impossible.
2. If user date format is validated with any specific format in GUI, then we can able to convert it With extra condition in server side coding.