在我的代码中,我必须将字符串值(输入)转换为java.sql.Date format。我面临的问题是,输入的日期格式是未定义的,它可以是任何格式。例如,输入字符串可以是"Jan 10,2014"、"01-10-2014"或"2014/Jan/10"。因此,现在我需要将此输入值转换为java.sql.Date(DD/MMMM/YYYY)。有什么方法可以实现这种转换吗?
发布于 2014-03-25 16:38:04
这是不可能的。
您不能区分dd/MM/yyyy和MM/dd/yyyy。
你真的需要知道格式,否则你的程序可能不会按照你想要的方式运行。
发布于 2014-03-25 16:39:45
尝试使用SimpledateFormat来使用上面提到的所有模式的List。
如下所示:
SimpleDateFormat format1 = new SimpleDateFormat("MMM dd,yyyy");
SimpleDateFormat format2 = new SimpleDateFormat("MM-dd-yyyy");
SimpleDateFormat format3 = new SimpleDateFormat("yyyy/MMM/dd");
// Note: be sure about the format, or else you may end up assigning incorrect values
List<DateFormat> list = new ArrayList<DateFormat>();
list.add(format1);
list.add(format2);
list.add(format3);
for (DateFormat format : list) {
try {
System.out.println(format.parse("Jan 10,2014"));
// Match found. Take action
} catch (ParseException exception) {
// Ignore. Try other pattern
}
}https://stackoverflow.com/questions/22629084
复制相似问题