0

我正在为 Android OS 编写一个应用程序,我需要在 SQLite DB 中存储一些时间值。我一直在使用 android.text.format.Time 将时间值存储在应用程序中,然后将值作为毫秒作为 REAL 值插入到数据库中。在 SDK 模拟器上,一切正常。在我有机会测试我的应用程序的唯一一部手机上(到目前为止),我的持续时间代码没有按预期工作。一些相关代码:

private static final String DATABASE_CREATE =
    "create table " + DATABASE_TABLE + " ("
     + KEY_ROWID + " integer primary key autoincrement, "
     + KEY_START + " REAL, "
     + KEY_STOP + " REAL, "
     + KEY_DUR + " REAL );";

...

private SQLiteDatabase mDb;
ContentValues timerValues = new ContentValues();

...

timerValues.put(KEY_START, stime.toMillis(false));
timerValues.put(KEY_STOP, etime.toMillis(false));
timerValues.put(KEY_DURATION, stime.toMillis(false)-etime.toMillis(false));
int result = mDb.insert(DATABASE_TABLE, null, timerValues);

我从两个使用稍微不同的代码位的单独函数中提取这些数据,两者都使用 Time.set(long millis),都给出了不正确的结果:开始和停止值恢复正确,但持续时间过长 17 小时。我是否遗漏了一些关于计算持续时间的信息,或者这似乎只是这个特定机器人有一些“特别”的地方?我将在周一测试另一个机器人,但任何想法都会受到赞赏。

4

2 回答 2

1

除了 Currie 先生关于列名的注释之外,还有一个问题是为什么您首先要浪费存储空间KEY_DURATION。它可以从KEY_START和计算KEY_STOP

SELECT start, stop, dur=stop-start FROM whatever

此外,android.text.format.Time只有秒精度,所以如果你需要毫秒,你不应该使用那个类。

If none of those help or are deemed suitable, try logging the value you are putting in KEY_DURATION, to see if the problem is in your calculation or in how it is being stored.

于 2010-04-24T11:32:29.720 回答
0

The issue actually turned out to be caused by the time zone settings on the phone. It appears that Time.toMillis will export the time as milliseconds from epoch, UTC. When setting time using Time.set(long millis), Time assumes that millis is milliseconds from Epoch, UTC. When you then request Time.format("%T"), Time returns a HH:MM:SS string adjusted to the local TZ. This makes sense unless you are using Time to measure a duration, in which case some effort should probably be used to account for the TZ adjustment. So, what I expected to be an elapsed time of say, 20 minutes, turned out to be represented by Time as 17:20:00 on the day before Epoch (MST or GMT-7). Nice little undocumented behavior.

In my application, I opted to write a simple utility class to handle converting to milliseconds to an appropriate string. Hopefully this post will save someone else some headache, as my google-fu revealed nothing related.

于 2010-04-25T23:47:52.713 回答