简体   繁体   English

如何在Android中从sqlite数据库存储和检索日期?

[英]How to store and retrieve Date from sqlite db in Android?

I'm storing date in sqlite database in Android as this: 我将日期存储在Android的sqlite数据库中,如下所示:

initialValues.put(KEY_TIME, time.getTime());

where time is an instance of Date (which has the correct time) and KEY_TIME is an integer column. 其中time是Date的实例(具有正确的时间),而KEY_TIME是整数列。

Once stored, when I retrieve it with a query such as this: 一旦存储,当我使用如下查询来检索它时:

String selectQuery = "SELECT  * FROM " + TABLE_NAME + " order  by date(" + KEY_TIME + ") DESC" ;

I never get the data with the recent one first. 我从来没有获得过最近的数据。

I get spurious time which is almost 40 years old. 我得到了近40岁的虚假时间。 Where am I going wrong? 我要去哪里错了?

java.util.Date.getTime() returns the number of milliseconds since the start of 1970 (epoch time). java.util.Date.getTime()返回自1970年开始(毫秒时间)以来的毫秒数。 SQLite can deal with Unix epoch time, which is the same value, but expressed in seconds (see java.util.Date.getTime() ). SQLite可以处理Unix纪元时间,该时间是相同的值,但以秒表示(请参见java.util.Date.getTime() )。

The mismatch of seconds and milliseconds is the reason you are seeing incorrect dates. 秒和毫秒的不匹配是您看到错误日期的原因。

You can divide the value by 1000 to get Unix style epoch time, and specify 'unixepoch' (see SQLite Time & Date Functions ) to SQLite's date function, eg: 您可以将值除以1000得到Unix风格的时代时间,并为SQLite的日期函数指定'unixepoch'(请参见SQLite时间和日期函数 ),例如:

SELECT date(KEY_TIME / 1000, 'unixepoch') FROM TABLE_NAME

If you are using a java.sql.Date it is the same (that class extends java.util.Date ). 如果您使用的是java.sql.Date ,则它是相同的(该类扩展了java.util.Date )。

However, as 323go mentioned in the question comments, just sort directly by KEY_TIME , which will give you the sort order you are looking for. 但是,正如问题注释中提到的323go一样,只需直接按KEY_TIME排序即可,这将为您提供所需的排序顺序。

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

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