You just can't do this because you have no idea what's in the string. Maybe the datestr in your code is like this "abcdredsad". If your are sure that this datestr object is a date string,and you just want to change the formatter from "yyyyMMdd HH:mm:ss" to "yyyy-MM-dd HH:mm:ss", try this.
public static void main(String[] args) {
String date = StringToDate("20160928 15:00:00");
System.out.println(date);
}
public static String StringToDate(Object datestr) {
Date d = new Date();// note: set a default value here
Date date;
if (datestr == null)
return null;
// you must know the old pattern of the datestr in your code
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
try {
d = sdf.parse(datestr.toString());// if your formatter is wrong, exception occurs here.
} catch (ParseException e) {
e.printStackTrace();
}
date = new Date(d.getTime());// if d didn't have a default value, wrong here.
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(date);
}