日期:2014-05-16 浏览次数:20857 次
在windows下使用DateFormat的parse方法,将字符中转化为Date类型时,一切正常。可安装到Linux下,就出现了ParseException异常。代码如下:
???? ??? public Date toDateTime(String str){ 
??????? ??? ??? Date dt = new Date(); 
??????? ??? ??? try{ 
?????????? ?? ? ??? ??? DateFormat df;
??????????? ??? ??? ??? df = DateFormat.getDateTimeInstance();? 
??????????? ??? ??? ??? dt = df.parse(str); 
??????? ??? ??? } 
??????? ??? ??? catch(ParseException e){ 
??????????? ??? ??? ??? System.err.println(e); 
??????? ??? ??? } 
??????? ??? ??? return dt; 
??? ??? }
我执行toDateTime("2005-5-1 12:00:00"),在windows下正常,Linux下出现ParseException异常。看来是Linux下的DateFormat对象不认识"2005-5-1 12:00:00"这种格式的字符串,所以转换不了(需进一步老确认)。
由于时间来不及,我赶紧换了另外一种方法。新的代码在Linux下运行正常。修改后的代码如下:
???? ??? public Date toDate(String str){ 
??????? ??? ??? Date dt = new Date(); 
??????? ??? ??? String[] parts = str.split("-"); 
???????? 
??????? ??? ??? if(parts.length >= 3){ 
??????????? ??? ??? ??? int years = Integer.parseInt(parts[0]); 
??????????? ??? ??? ??? int months = Integer.parseInt(parts[1]) - 1; 
?????????? ?? ??? ??? ? int days = Integer.parseInt(parts[2]); 
?????????? ?? ??? ??? ? int hours = 0; 
?????????? ?? ??? ??? ? int minutes = 0; 
?????????? ?? ??? ??? ? int seconds = 0; 
???????????? 
?????????? ?? ??? ??? ? GregorianCalendar gc = new GregorianCalendar(years,months,
??? ??? ??? ??? ??? ??? ??? ??? ??? ??? days,hours,minutes,seconds); 
???????????? 
??????????? ??? ??? ??? dt = gc.getTime();???????????? 
?????? ?? ??? ? }
??? ??? ??? ??? return dt; 
??? ??? }
我的日期字符串格式是"yyyy-MM-dd-HH-mm-ss"的,所以代码如上。要转化别的格式,截取字符中的时候会不一样。但,它的核心代码是 "GregorianCalendar gc = GregorianCalendar(years, months, days, hours, minutes, seconds);"。也就是用GregorianCalendar类来进行String到Date类型的转换。