如何将小时/分钟保存到数据库SQLiteOpenHelper中?

时间:2018-04-07 12:27:35

标签: java android android-sqlite localtime

如何在数据库SQLiteOpenHelper中保存小时/分钟? 时钟和分钟格式?例如:12:4000:00

2 个答案:

答案 0 :(得分:0)

只需将其保存为String并将其格式化,就像每次使用时一样。

Sqlite没有DATETIME类型。

答案 1 :(得分:0)

您可以通过多种方式保存此类数据,如文本/字符串,整数0-1440,两个整数(一个用于小时,一个用于分钟),长度为十进制。

选择可能取决于后续使用,如果它只是显示然后文本/字符串可能是合适的。如果要执行计算,则text / string可能会导致复杂的过程(请参阅下面示例中的getElapsedTimeForAllTimesAsInt)。

要考虑的一个因素是如何/如果SQLite日期时间函数会有什么好处,如果是这样,那么以它识别的格式之一保存是明智的(HH:MM(24小时制)就是这样的格式) 。必读为SQL As Understood By SQLite - Date And Time Functions

下面是一个可以节省时间(以及也许不怎么样)的工作示例: -

数据库助手 - SOD49707387DBHelper.java

  • 这包括插入数据的方法(虽然没有验证数据)
    • insertTime
  • 还包括3种提取数据的方法: -
    • getAllTimesAsCursor将所有行检索为Cursor。
    • getAllTimesAsStringArray将所有行检索为String [] (请注意,它使用getAllTimesAsCursor
    • getElapsedTimeOfAllTimesAsInt,返回最早和最晚时间之间的分钟数。这是为了演示如何转换/提供非sqlite日期格式可能会有点复杂(注意它有缺陷而且不打算使用)
    • 为方便起见,课程/文件名称很长,您可能会使用不同的名称。

: -

public class SOD49707387DBHelper extends SQLiteOpenHelper {

    public static final String DBNAME = "mydatabase";
    public static final int DBVERSION = 1;
    public static final String TBNAME_TIME = "mytimesave";
    public static final String TIME_COL_TIME = "_time";

    SQLiteDatabase mDB;
    public SOD49707387DBHelper(Context context) {
        super(context, DBNAME, null, DBVERSION);
        mDB = this.getReadableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String crtsql = "CREATE TABLE IF NOT EXISTS " + TBNAME_TIME + "(" +
                TIME_COL_TIME + " TEXT" +
                ")";
        db.execSQL(crtsql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    // Not assumes that time is valid
    public boolean insertTime(String time) {
        ContentValues cv = new ContentValues();
        cv.put(TIME_COL_TIME,time);
        return  (mDB.insert(TBNAME_TIME,null,cv) > 0);
    }

    public Cursor getAllTimesAsCursor() {
         return mDB.query(TBNAME_TIME,
                null,
                null,
                null,
                null,
                null,
                null);
    }

    public String[] getAllTimesAsStringArray() {
        Cursor csr =getAllTimesAsCursor();
        String[] rv = new String[csr.getCount()];
        while (csr.moveToNext()) {
            rv[csr.getPosition()] = csr.getString(csr.getColumnIndex(TIME_COL_TIME));
        }
        csr.close();
        return rv;
    }

    /*
     NOTE!! equates to query
         SELECT
             max((substr(_time,1,2) * 60) + substr(_time,4,2))
             -
             min((substr(_time,1,2) * 60) + substr(_time,42))
         AS elapsedminutes
         FROM mytimesave;
      NOTE!!! inherently unreliable as assumes all rows are valid
     */
    public int getElapsedTimeOfAllTimesAsInt() {
        int rv = 0;
        String result_column =
                "" +
                        "max((substr(" +
                        TIME_COL_TIME +
                        ",1,2) * 60) + substr(" +
                        TIME_COL_TIME + ",4,2))" +
                        " - " +
                        " min((substr(" +
                        TIME_COL_TIME +
                        ",1,2) * 60) + substr(" +
                        TIME_COL_TIME +
                        ",4,2))" +
                        " AS " + TIME_COL_TIME //??? hijack _time column
                ;
        Cursor csr = mDB.query(
                TBNAME_TIME,
                new String[]{result_column},
                null,
                null,
                null,
                null,
                null);
        if (csr.moveToFirst()) {
            rv = csr.getInt(csr.getColumnIndex(TIME_COL_TIME));
        }
        csr.close();
        return rv;
    }
}

调用Activity - MainActivity.java

public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SO49707387(); // call method for this answer
    }

    private void SO49707387() {
        // Instantiate DBHelper instance
        SOD49707387DBHelper dbhlpr = new SOD49707387DBHelper(this);
        // Insert some data (2 rows each time App is run)
        dbhlpr.insertTime("12:00");
        dbhlpr.insertTime("08:00 AM");
        // Get database information (*1)
        CommonSQLiteUtilities.logDatabaseInfo(dbhlpr.getWritableDatabase());
        // Get all times as a Cursor
        Cursor csr = dbhlpr.getAllTimesAsCursor();
        // traverse the Cursor writing data to the log
        while (csr.moveToNext()) {
            Log.d("TIME_VIA_CURSOR",
                    csr.getString(
                            csr.getColumnIndex(
                                    SOD49707387DBHelper.TIME_COL_TIME)
                    )
            );
        }
        csr.close(); //<<< Should always close cursor when done with them

        // get all times as a String array
        String[] times = dbhlpr.getAllTimesAsStringArray();
        // traverse the array writing data to the log
        for (String s: times) {
            Log.d("TIME_VIA_ARRAY",s);
        }
        // Calculate and print the elapsed time
        // (largest time - smallest time)
        // i.e. 12:00 - 08:00 = 240 minutes = 4 hours
        Log.d("ELAPSED",
                "The elapsed time in minutes is " +
                        String.valueOf(dbhlpr.getElapsedTimeOfAllTimesAsInt())
        );
    }
}
  • 请注意 CommonSQLiteUtilities 类的来源here

测试结果(来自日志): -

04-08 03:33:00.055 1945-1945/? D/SQLITE_CSU: DatabaseList Row 1 Name=main File=/data/data/soanswers.soanswers/databases/mydatabase
    Database Version = 1
    Table Name = android_metadata Created Using = CREATE TABLE android_metadata (locale TEXT)
    Table = android_metadata ColumnName = locale ColumnType = TEXT Default Value = null PRIMARY KEY SEQUENCE = 0
    Table Name = mytimesave Created Using = CREATE TABLE mytimesave(_time TEXT)
    Table = mytimesave ColumnName = _time ColumnType = TEXT Default Value = null PRIMARY KEY SEQUENCE = 0
04-08 03:33:00.059 1945-1945/? D/TIME_VIA_CURSOR: 12:00
    08:00 AM
04-08 03:33:00.059 1945-1945/? D/TIME_VIA_ARRAY: 12:00
    08:00 AM
04-08 03:33:00.059 1945-1945/? D/ELAPSED: The elapsed time in minutes is 240