我很难将以下日期字符串"2014-07-10T11:31:35"
转换为android中的java Date对象。
所以Date date = new Date("2014-07-10T11:31:35");
返回null,这会导致空引用异常
public class DateUtil {
public static String FromIsoString(String datestring)
{
String formattedDateString = "";
try {
if (!datestring.isEmpty()) {
Date date = new Date(date string);//-->>>> returns null
String format = "dd/MM/yyyy";
Locale locale = Locale.ENGLISH;
formattedDateString = FromIsoString(date, format, locale);
}
}
catch(Exception ex)
{
Log.e(ex.getLocalizedMessage(),"FromUtcString");
}
return formattedDateString;
}
public static String FromIsoString(Date date, String format, Locale locale){
String dateString = null;
try
{
dateString = new SimpleDateFormat(format, locale).format(date);
}catch (Exception ex)
{
Log.e(ex.getLocalizedMessage(),"FromString");
}
return dateString;
}
}
答案 0 :(得分:7)
/**
* Format date with specified Date format
* @param dateString
* @param inFormat format of input date
* @param outFormat format of result date
* @return dateString
*/
public static String formatDate(String dateString, String inFormat, String outFormat){
DateFormat inFormatter = new SimpleDateFormat(inFormat);
inFormatter.setLenient(false);
DateFormat outFormatter = new SimpleDateFormat(outFormat);
Date date = null;
try {
date = inFormatter.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
return "";
}
return outFormatter.format(date);
}
并将其称为formatDate("2014-07-10T11:31:35"", inFormat, outFormat)
其中inFormat = "yyyy-MM-dd'T'HH:mm:ss"
和outFormat = "dd/MM/yyyy"