DateFormat解析错误
问题描述:
我有一个日期进来。所以例如02/16/2012。我需要做的是使用我的数据库格式将其转换为2012-02-16。我想这将是非常简单的。但我无法工作。这是我的日期解析器。DateFormat解析错误
String endDateString = "02/16/2012"
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");
endDate = dateFormat.parse(endDateString)
有什么建议吗?谢谢。
答
你应该分析它从一个正确的格式,然后用另一个正确的格式转换为TO字符串。你在做什么 - 试图用yyyy-MM-dd
格式来解释MM/dd/yyyy
格式的日期,即不正确。
样品
public static void main(String[] args) throws ParseException {
SimpleDateFormat sourceFormat = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat destinationFormat = new SimpleDateFormat("yyyy-MM-dd");
String sourceDateString = "02/16/2012";
String destinationDateString;
Date dat; // this object stores "perfect" date object
// interpreting string with input format and converting it to date
dat = sourceFormat.parse(sourceDateString);
// expressing date object as string in destination format
destinationDateString = destinationFormat.format(dat);
System.out.format("Done from %s to %s\n", sourceDateString, destinationDateString));
}
答
你用错了格式解析
new SimpleDateFormat("MM/dd/yyyy");
答
您指定的日期格式必须与您输入的日期格式如下所示:
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
答
你想要做的是解析输入格式为Date
对象
final SimpleDateFormat idf = new SimpleDateFormat("MM/dd/yyyy");
final Date indate = idf.parse("02/16/2012");
然后重新格式化Date
对象的格式,你的愿望
final SimpleDateFormat odf = new SimpleDateFormat("yyyy-MM-dd");
final String s = odf.format(indate);
答
这段代码可以告诉你如何完成它。
SimpleDateFormat inputDateFormat = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String endDateString = "02/16/2012";
String endDate = outputDateFormat.format(inputDateFormat.parse(endDateString));
答
您还可以在数据库级别转换的日期。例如MySQL有一个函数STR_TO_DATE。在你的情况下,这将是STR_TO_DATE('02/16/2012','%m /%d /%Y')