2016-03-28 131 views
-3

我有一个要求,我将日期转换为一种格式到另一个,我可以得到一个不可解析的日期异常。该类的代码如下Java日期解析异常

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; 
    } 
} 
+1

首先,您需要从String创建/解析Date对象,然后将日期对象转换为String或任何您想要的。 – kosa

+0

你的stringDate格式和解析格式不一样。请参阅:https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html – kevingreen

+1

'“星期五Feb 26 14:14:40 CST 2016”'看起来不像它有一个'MM-dd-yyyy'的格式' – Bohemian

回答

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); 
} 
+0

这只打印日期作为输入,我希望输出日期为m/dd/yyyy格式 – developer2015