问题
I want to parse a string from string to date ,Date is of format like Tuesday March 19,2015
. I want to parse and format it as yyyy-dd-mm
format. The below code gives me exception that "unparceble date".
Code :
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
try {
date1 = df1.parse(currentDate);
System.out
.println("============my formated date====================" + date1.toString());
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
cal.add(Calendar.DATE, 10); // add 10 days
date1 = cal.getTime();
System.out.println("==============added date==============" + date1.toString());
回答1:
I have created one common function for convert date format. You have to pass old Date format, new date format and date.
public static String convertDateFormat(String oldFormat, String newFormat, String inputDate)
{
DateFormat theDateFormat = new SimpleDateFormat(oldFormat);
Date date = null;
try
{
date = theDateFormat.parse(inputDate);
}
catch (ParseException parseException)
{
// Date is invalid. Do what you want.
}
catch (Exception exception)
{
// Generic catch. Do what you want.
}
theDateFormat = new SimpleDateFormat(newFormat);
return theDateFormat.format(date).toString();
}
// Call funcation
String convertedDate = convertDateFormat("EEEE MMM dd,yyyy","yyyy-MM-dd",dateToConvert);
回答2:
You must parse it into the date of your current format before format it to another date
DateFormat df_parse = new SimpleDateFormat("EEEE MMM dd,yyyy");
Date date_parse = df_parse.format(currentDate);
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
date1 = df1.parse(date_parse);
来源:https://stackoverflow.com/questions/29092277/parse-a-date-from-string-gives-exception-in-android