我想在sqlitedatabase中只插入当前日期。根据我的理解,日期必须是整数。我想以一种我以后可以查询日期的方式插入日期。我怎样才能做到这一点? 感谢
public class MyDatabase{
public static final String KEY_ROWID ="_id";
public static final String KEY_NAME ="persons_name";
public static final String KEY_ADDRESS ="persons_address";
private static final String DATABASE_NAME = "PersonsDatabase";
private static final String DATABASE_TABLE = "personsTable";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_ADDRESS + " TEXT NOT NULL);"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public long createEntry(String name, String address) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_NAME , name);
cv.put(KEY_ADDRESS, address);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
答案 0 :(得分:0)
您无法在数据库中存储日期值,您只能存储字符串。您可以通过以下方式将当前日期转换为字符串:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
...
cv.put(KEY_DATE, sdf.format(new Date(System.currentTimeMillis())));
您可以通过以下方式从db中读取日期:
String tmpString = curs.getString(curs.getColumnIndex(KEY_DATE));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dateVariable = sdf.parse(tmpString);
<强>更新强>
此外,您可以将timeatamp存储为长值。例如:
cv.put(KEY_DATE, System.currentTimeMillis());
要查询过去7天您需要这样做:
long sevenDaysAgo = System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 7;
Cursor curs = sqLiteDB.query(DATABASE_TABLE, null, KEY_DATE + " > " + sevenDaysAgo, null, null, null, null);
答案 1 :(得分:0)
将列创建为:
col_name TIMESTAMP DEFAULT CURRENT_TIMESTAMP
插入时忽略col_name(这将自动添加)。如果你想获得日期,你可以这样做:
private Date getDateFromCursor(Cursor cursor) {
Timestamp dateTime = Timestamp.valueOf(cursor.getString(cursor.getColumnIndex("col_name")));
int rawOffset = TimeZone.getDefault().getRawOffset();
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateTime);
calendar.add(Calendar.MILLISECOND, rawOffset);
return calendar.getTime();
}