SQLite存储日期问题

时间:2016-04-21 09:56:31

标签: android sqlite

我试图在SQLite上存储用户输入的日期,但是我设法弄清楚的是如何添加由android设备设置的当前日期。我希望用户能够使用expirydate和recieveddate的日期,而不是从设备设置中获取它们。

这是我的代码..

package com.example.bash1.sqlitediss;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DatabaseHelper extends SQLiteOpenHelper {
// Database name
public static final String DATABASE_STOCKDB = "Stock.db";
// Column names
public static final String TABLE_NAME = "stock_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "Name";
public static final String COL_3 = "Datereceived";
public static final String COL_4 = "Expirydate";


public DatabaseHelper(Context context) {
    super(context, DATABASE_STOCKDB, null, 1);

}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table " + TABLE_NAME + " (" + COL_1 + " INTEGER PRIMARY KEY," + COL_2 + " TEXT," + COL_3 + " DATE," + COL_4 + " DATE" + ")");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);

    onCreate(db);
}

public boolean insertData(String Name, String Datereceived, String Expirydate){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_2, Name);
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    contentValues.put(COL_3, dateFormat.format(new Date()));
//    contentValues.put(COL_3, Datereceived);
    contentValues.put(COL_4, dateFormat.format(new Date()));
    long result = db.insert(TABLE_NAME,null,contentValues);
    if (result == -1 )
        return false;
    else
        return true;

}

// Calls all data for the View Database Button
public Cursor getAllData (){
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
    return res;

}

}

2 个答案:

答案 0 :(得分:0)

您可以使用ORDER BY按升序或降序排序,下面是查询

这是用于升序降序将ASC单独更改为DESC并放置适当的表名和列名。 DATE_ADD 功能可用于执行此操作。

注意:当前日期应采用sql日期格式。

"select * from " + TABLE_NAME + "column_name < (DATE_SUB(yourCurrentDate, INTERVAL 30 DAY));"

答案 1 :(得分:0)

以下是查询的快照以及如何在表格中存储日期(即日期格式)。希望这会有所帮助。

enter image description here
更新:
获取 currentDay-30days 的查询将如下所示

Calendar calendar=Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, -30);
String last30Days=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
System.out.println(last30Days);

//your query look like this
//"SELECT * FROM your_table where date_column_name>'"+last30Days+"'"
//SELECT * FROM your_table where date_column_name>'2016-03-20 00:00:00'