gpt4 book ai didi

Android SQLite 数据库 - 按日期排序

转载 作者:行者123 更新时间:2023-11-30 03:33:35 26 4
gpt4 key购买 nike

我想按日期对我的文章进行排序。为此,我想我必须将我的日期从字符串转换为日期格式。我的日期是 Fri,12 Feb 2012 12:23:32

我一直在尝试这样做:

private String formatDateTime(Context context, String timeToFormat) throws java.text.ParseException {

String finalDateTime = "";

SimpleDateFormat iso8601Format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss.SSSZ",Locale.UK);

Date date = null;
if (timeToFormat != null) {
try {
date =(Date) iso8601Format.parse(timeToFormat.trim());
} catch (ParseException e) {
date = null;
}

if (date != null) {
long when = date.getTime();
int flags = 0;
flags |= android.text.format.DateUtils.FORMAT_SHOW_TIME;
flags |= android.text.format.DateUtils.FORMAT_SHOW_DATE;
flags |= android.text.format.DateUtils.FORMAT_ABBREV_MONTH;
flags |= android.text.format.DateUtils.FORMAT_SHOW_YEAR;

finalDateTime = android.text.format.DateUtils
.formatDateTime(context, when
+ TimeZone.getDefault().getOffset(when),
flags);
}
}
return finalDateTime;
}

然后:

public Cursor getAllData() {// DBHelper.ROWID+" DESC"

String buildSQL = null;

try {
buildSQL = "SELECT * FROM " + DBHelper.DATABASE_TABLE
+ " ORDER BY " + formatDateTime(ourContext,DBHelper.DATE)+ " ASC";
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return ourDatabase.rawQuery(buildSQL, null);
}

但是我在

中得到一个 NullPointerException
return ourDatabase.rawQuery(buildSQL, null);

另一种方式:

public Cursor getAllData() {

String buildSQL = null;

try {
buildSQL = "SELECT * FROM " + DBHelper.DATABASE_TABLE
+ " ORDER BY " + formatDateTime(DBHelper.DATE)+ " ASC";
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return ourDatabase.rawQuery(buildSQL, null);
}

private Date formatDateTime(String timeToFormat) throws java.text.ParseException {

SimpleDateFormat curFormater = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss.SSSZ",Locale.ENGLISH);
Date dateObj = (Date) curFormater.parse(timeToFormat);

return dateObj;
}

最佳答案

为什么不用上面的函数strftime()呢?直接在 SQLIte 中?更干净、更快。

关于Android SQLite 数据库 - 按日期排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17000228/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com