Java String to Date, ParseException

淺唱寂寞╮ 提交于 2019-12-20 07:21:50

问题


I have a string named DateCompareOld, it has the value "Fri Aug 12 16:08:41 EDT 2011". I want to convert this to a date object.

 SimpleDateFormat dateType =  new SimpleDateFormat("E M dd H:m:s z yyyy");
 Date convertDate = dateType.parse(DateCompareOld);

But everytime I try this, I get a parse exception. I have tried other SimpleDateFormat formatting criteria, but it always fails.

Suggestions?


回答1:


Try this format:

EEE MMM dd HH:mm:ss zzz yyyy

Quick test:

public static void main(String[] args) throws Exception {
    DateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
    System.out.println(df.parse("Fri Aug 12 16:08:41 EDT 2011"));
}

// outputs
Fri Aug 12 15:08:41 CDT 2011

Output is in CDT, since that's where I am, but the value is right.




回答2:


DateFormat dateType =  new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
dateType.setLenient(false);
Date convertDate = dateType.parse(DateCompareOld);



回答3:


Note the String passed to SimpleDateFormat() should be corrected to "EEE MMM dd HH:mm:ss z yyyy"

Here is the code:

import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.ParseException;
public class DateTest{
public static void main(String []args){
    String DateCompareOld = "Fri Aug 12 16:08:41 EDT 2011";
    SimpleDateFormat dateType =  new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
    Date convertDate = new Date();
    try{
     convertDate = dateType.parse(DateCompareOld);
    }catch(ParseException pex){
        pex.printStackTrace();
    }
    System.out.println(convertDate.toString());
  }

}


来源:https://stackoverflow.com/questions/7045931/java-string-to-date-parseexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!