java 中的字符串到 sql 日期的转换

string to sql date conversion in java

SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");    
String stringdate = "Wed Jan 01 00:00:00 CST 2014";
Date stringFromDate = null;
try {
  Date dtt= formatter.parse(stringDate);
  System.out.println(dtt);
} 
catch (ParseException e1) {
  e1.printStackTrace();
}

我收到异常 java.text.ParseException: Unparseable date: "Wed Jan 01 00:00:00 CST 2014" 尝试了很多次,但没有用。

这里我有 "stringdate " 作为固定格式,我必须以 MM/DD/yyyy 格式显示。那是我的要求。

您为 SimpleDateFormat 使用的模式是错误的。

此模式应符合您给定的日期格式:

EEE MMM dd HH:mm:ss Z yyyy

创建 SimpleDateFormat 时使用它:

SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");

有关不同字母含义的更多信息,请查看 documentation for SimpleDateFormat

另请注意,SimpleDateFormat.parse() 不会给您标题中提到的 java.sql.Date,而是 java.util.Date

编辑:以不同的格式输出日期,您需要创建第二个SimpleDateFormat表示所需的输出格式。然后你可以使用 SimpleDateFormat.format():

将它转换回你想要的字符串
SimpleDateFormat outputFormat = new SimpleDateFormat("MM/dd/yyyy");
String output = outputFormat.format(yourDate);

System.out.println(output);

总而言之,结果如下代码:

String input = "Wed Jan 01 00:00:00 CST 2014";
SimpleDateFormat inputFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");

try {
    Date date = inputFormat.parse(input);

    SimpleDateFormat outputFormat = new SimpleDateFormat("MM/dd/yyyy");
    String output = outputFormat.format(date);

    System.out.println(output); // 01/01/2014

} catch (ParseException e) {
    e.printStackTrace();
}

要在 MM/dd/yyyy 中获取日期,请尝试使用第二个 SimpleDateFormat 作为:

new SimpleDateFormat("MM/dd/yyyy");