我有一个要求,我将Date转换为一种格式到另一种格式,我得到一个不可解析的日期例外。 Class的代码粘贴在
下面public class DateTester {
public static void main(String[] args) {
// TODO Auto-generated method stub
String stringDate = "Fri Feb 26 14:14:40 CST 2016";
Date date = convertToDate(stringDate);
System.out.println(date);
}
public static Date convertToDate(String date) {
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
Date convertedCurrentDate = null;
try {
convertedCurrentDate = sdf.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
}
return convertedCurrentDate;
}
}
答案 0 :(得分:1)
使用以下格式:
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
代码:
public class StackOverflowSample {
public static void main(String[] args) {
String stringDate = "Fri Feb 26 14:14:40 CST 2016";
Date date = convertToDate(stringDate);
System.out.println(date);
}
public static Date convertToDate(String date) {
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date convertedCurrentDate = null;
try {
convertedCurrentDate = sdf.parse(date);
} catch (Exception e) {
System.out.println(e.getMessage());
}
return convertedCurrentDate;
}
}
来源:https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
编辑:如果你想返回格式为" MM-dd-yyyy"
的日期字符串public static void main(String[] args) {
String stringDate = "Fri Feb 26 14:14:40 CST 2016";
Date date = convertToDate(stringDate);
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
String dateFormatted = sdf.format(date);
System.out.println(dateFormatted);
}