简体   繁体   English

Java 和 SQLite 之间的时间戳差异

[英]TimeStamp Difference Between Java and SQLite

Hello I have and SLQLite database in which I have table water_logs你好,我有 SLQLite 数据库,其中有表 water_logs

CREATE TABLE water_logs( 
_id INTEGER PRIMARY KEY AUTOINCREMENT,
amount REAL NOT NULL,
icon INTEGER NOT NULL,
date INTEGER NOT NULL);

I store date in milliseconds.我以毫秒为单位存储日期。

Calendar cal = Calendar.getInstance(); 
cal.getTimeInMillis();

My problem is I want to get the day from the my date column using strftime function.我的问题是我想使用strftime函数从我的日期列中获取日期。 The problem is tjat java calendar timestamp is different from SLQLite time stamp问题是 tjat java 日历时间戳与 SLQLite 时间戳不同

1436859563832 --> result from cal.getTimeInMillis();

1436607407--> SELECT strftime('%s','now')

What I'm actually trying to do is to group records by day.我真正想做的是按天对记录进行分组。 The following SQL query works just fine if value of SELECT strftime('%s','now') is paste in the date column如果 SELECT strftime('%s','now') 的值粘贴在日期列中,则以下 SQL 查询工作正常

SELECT SUM(amount), date(`date`) FROM water_logs
GROUP BY date(`date`, 'unixepoch')

在此处输入图片说明

在此处输入图片说明

在此处输入图片说明

Seems to me that you are using 2 different value types.在我看来,您正在使用 2 种不同的值类型。

When you use当你使用

Calendar cal = Calendar.getInstance(); 
long time = cal.getTimeInMillis();

The output value is in Milliseconds , as described here .输出值以毫秒为单位,如所描述这里

While when you use当你使用

strftime('%s','now')

The output value is in Seconds , as described here .输出值是以为单位,如所描述这里

So, that might be the cause for the mismatch between the two values.因此,这可能是两个值之间不匹配的原因。 Of course that the value in seconds might undergo some rounding which might change its value a little.当然,以秒为单位的值可能会进行一些舍入,这可能会稍微改变其值。

I will try to provide you the best way to store Dates in SQLite database.我将尽力为您提供在 SQLite 数据库中存储日期的最佳方式。

1) Always use integers to store the dates. 1) 始终使用整数来存储日期。

2) Use this utility method to store the dates into the database, 2)使用此实用程序方法将日期存储到数据库中,

public static Long saveDate(Date date) {
    if (date != null) {
        return date.getTime();
    }
    return null;
}

Like,喜欢,

ContentValues values = new ContentValues();
values.put(COLUMN_NAME, saveDate(entity.getDate()));
long id = db.insertOrThrow(TABLE_NAME, null, values);

3) Use this utility method to load date, 3)使用此实用方法加载日期,

public static Date loadDate(Cursor cursor, int index) {
    if (cursor.isNull(index)) {
        return null;
    }
    return new Date(cursor.getLong(index));
}

like,喜欢,

entity.setDate(loadDate(cursor, INDEX));

4) You can also order the data by date using simple ORDER clause, 4) 您还可以使用简单的 ORDER 子句按日期对数据进行排序,

public static final String QUERY = "SELECT table._id, table.dateCol FROM table ORDER BY table.dateCol DESC";

//...

    Cursor cursor = rawQuery(QUERY, null);
    cursor.moveToFirst();

    while (!cursor.isAfterLast()) {
        // Process results
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM