我正在尝试编写一种方法,将日期String
转换为Long
。我无法判断我是否错误地编写了方法,或者SimpleDateFormat
中的日期格式是否不正确。我从SQLite数据库中获取字符串,如下所示:
DBAdapter info = new DBAdapter(this);
info.open();
infoStrArray = info.displayEventsInList4();
info.close();
startDateStr = getLongDate(Long.parseLong(infoStrArray[2]));
endDateStr = getLongDate(Long.parseLong(infoStrArray[3]));
textview_TV.setText(startDateStr + ", " endDateStr);
在数据库中,日期字符串的写法如下:“2014_06_11 10:55:00”。所以在我的getLongDate方法中,我编写了SimpleDateFormat格式,如下所示:yyyy_MM_dd HH:mm:ss
。这是完整的方法:
public static String getLongDate(long milliSeconds) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
return sdf.format(calendar.getTime());
}
然后,运行代码我收到错误:java.lang.NumberFormatException: 2014_06_11 10:55:00
。那么故障在哪里?方法写得不正确,我是不正确地调用方法,还是日期格式语法,还是我根本没看到的东西?
这是Igle让我走上正轨后的解决方案:
startDateLong = getLongDate3(infoStrArray[2]);
endDateLong = getLongDate3(infoStrArray[3]);
textview_TV.setText(String.valueOf(startDateLong) + ", " + String.valueOf(endDateLong));
public static long getLongDate3(String dateString) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd HH:mm:ss");
//This creates a date object from your string
Date date = null;
try {
date = sdf.parse(dateString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//getTime() always returns milliseconds since 01/01/1970
return date.getTime();
}
答案 0 :(得分:1)
请勿尝试解析字符串。
而是将字符串传递给getLongDate()
,如下所示:
public static String getLongDate(string dateString) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd HH:mm:ss");
//This creates a date object from your string
Date date = sdf.parse(dateString);
//getTime() always returns milliseconds since 01/01/1970
return date.getTime();
}