在windows下使用DateFormat的parse方法,将字符中转化为Date类型时,一切正常。可安装到Linux下,就出现了ParseException异常。代码如下:
/**
* windows下可以, linux上报错
* 看来是Linux下的DateFormat对象不认 识"2005-5-1 12:00:00"这种格式的字符串,所以转换不了
* @param dateStr
* @param formateStyle
* @return
*/
public static String dateFormate(String dateStr,String formateStyle){
DateFormat df = DateFormat.getDateTimeInstance();
try {
Date dd = df.parse(dateStr);
return DateUtil.formateStr(dd,formateStyle);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
我执行dateFormate(“2022-5-1 9:9:00”),在windows下正常,Linux下出现ParseException异常。看来是Linux下的DateFormat对象不认 识"2022-5-1 9:9:00"这种格式的字符串,所以转换不了。
由于没有找到更好的方法,我换了另外一种方法粗笨的方法。新的代码在Linux下运行正常。修改后的代码如下:
public static String dateFormateLinux(String dateStr,String formateStyle){
String result = "";
try {
Date dt = new Date();
String[] array = dateStr.split(" ");
String[] parts = array[0].split("-");
String[] parts2 = array[1].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;
if (parts2.length >= 3) {
hours = Integer.parseInt(parts2[0]);
minutes = Integer.parseInt(parts2[1]);
seconds = Integer.parseInt(parts2[2]);
}
GregorianCalendar gc = new GregorianCalendar(years, months,
days, hours, minutes, seconds);
dt = gc.getTime();
result = DateUtil.formateStr(dt, "yyyy-MM-dd HH:mm:ss");
}
}catch (Exception e){
e.printStackTrace();
}
return result;
}
我的日期字符串格式是"yyyy-MM-dd HH:mm:ss"的,所以代码如上。要转化别的格式,截取字符中的时候会不一样。但,它的核心代码是 “GregorianCalendar gc = GregorianCalendar(years, months, days, hours, minutes, seconds);”。也就是用GregorianCalendar类来进行String到Date类型的转换。
例:
public static void main(String[] args){
String aa = "2022-8-9 9:9:00";
Date dt = new Date();
String [] array = aa.split(" ");
String[] parts = array[0].split("-");
String[] parts2 = array[1].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;
if(parts2.length >= 3){
hours = Integer.parseInt(parts2[0]);
minutes = Integer.parseInt(parts2[1]);
seconds = Integer.parseInt(parts2[2]);
}
GregorianCalendar gc = new GregorianCalendar(years,months,
days,hours,minutes,seconds);
dt = gc.getTime();
System.out.println(dt);
System.out.println(DateUtil.formateStr(dt,"yyyy-MM-dd HH:mm:ss"));
}
}