问题
When running through the below code I am getting an UNPARSABLE DATE EXCEPTION
.
How do I fix this?
package dateWork;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateCreation {
/**
* @param args
*/
public static void main(String[] args) {
String startDateString = "2013-03-26";
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
Date startDate=null;
String newDateString = null;
try
{
startDate = df.parse(startDateString);
newDateString = df.format(startDate);
System.out.println(startDate);
} catch (ParseException e)
{
e.printStackTrace();
}
}
}
回答1:
You used wrong dateformat for month, also you should use the same delimiter as in your date.
If you date string is of format "2013/01/03"
use the same delimiter /
for the pattern "yyyy/MM/dd"
If your date string is of format "2013-01-03"
use the same delimiter '-' in your pattern "yyyy-MM-dd"
DateFormat df = new SimpleDateFormat("yyyy/mm/dd");
should be
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
From SimpleDateFormat Doc
MM---> month in an year
mm---> minutes in hour
回答2:
MM
instead of mm
-
instead of /
ie yyyy-MM-dd
as you are using -
in date string
回答3:
String startDateString = "2013-03-26";
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
you are using different pattern than what you are parsing.
either initialize this as DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
or this as String startDateString = "2013/03/26";
also look this article
回答4:
pass same format string in constructor of SimpleDateFormat("yyyy-mm-dd")
as your string date is "2013-03-26"
if your date is "2013/03/26" use
SimpleDateFormat("yyyy/mm/dd")
来源:https://stackoverflow.com/questions/15760248/how-to-create-date-object-from-string-value