我在这个问题上待了两天。这是该问题的延续:convert string to joda datetime gets stuck
我正在尝试执行一个简单的任务,将SQL SERVER ISO 8601字符串转换为DateTime或LocalDate。我尝试了所有方法,但是当涉及到调试器的实际转换时,程序游标只是用于思考而不会返回,即程序停留在该位置。
我非常绝望,我什至试图将String转换为Date(有效!),然后将Date转换为DateTime或LocalDate。所有人都有相同的结果,在转换的过程中,程序看起来像陷入了一个无休止的循环(风扇开始疯狂地工作)。
这是我这么简单的功能:
public static LocalDate SQLServerIso8601StringToLocalDate(String date) {
LocalDate dateToReturn = null;
DateFormat df = new SimpleDateFormat(CONSTS_APP_GENERAL.SQL_SERVER_DATE_FORMAT);
try {
Date tempDate = (Date) df.parse(date);
DateTime dt = new DateTime(tempDate);
dateToReturn = new LocalDate(tempDate);
} catch (ParseException e) {
// strToReturn = strSqlDate;
}
return dateToReturn;
/*
date = date.replace('T', ' ');
return SimpleIso8601StringToDateTime(date);
*/
//return LocalDate.parse(date, DateTimeFormat.forPattern(CONSTS_APP_GENERAL.SQL_SERVER_DATE_FORMAT));
/* DateTimeFormatter df = DateTimeFormat.forPattern(CONSTS_APP_GENERAL.SQL_SERVER_DATE_FORMAT_WITH_TZ);
return df.parseDateTime(date);
*/ }
这是我的字符串:
2014-01-01T00:00:00
也:
public static final String SQL_SERVER_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";
有任何想法吗?
最佳答案
public static Date getDateFromString(String format, String dateStr) {
DateFormat formatter = new SimpleDateFormat(format);
Date date = null;
try {
date = (Date) formatter.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}