比较日期(如字符串存储)在Android的SQLite数据库?字符串、日期、数据库、Android

2023-09-13 23:43:12 作者:久田樱子.

我存储日期为字符串在我的数据库,格式为:

I store dates as String in my database, in this format:

YYYY-MM-DD HH:MM:SS

这是支持的格式之一( http://www.sqlite.org/lang_datefunc.html )。现在,我想比较这些存储的日期(当然,字符串)与另一个日期。我的日期都存储在列 column_date ,所以我想这样的:

which is one of supported formats (http://www.sqlite.org/lang_datefunc.html). Now I want to compare these stored dates (well, strings) with another dates. My dates are stored in column column_date, so I'm trying this:

SELECT  * FROM MyTable
WHERE 
(Date(column_date) >= Date (2000-01-01) AND Datetime(column_date) <= Datetime (2050-01-01))

只要我阅读文档,的日期和时间函数使用的IS0-8601日期和时间格式的子集。该日期()函数返回的日期格式为:YYYY-MM-DD 所以我想,我这样做是正确的 - 我创建日期从存储字符串,并从另一个创建日期比较字符串。

As i read documentation, The date and time functions use a subset of IS0-8601 date and time formats. The date() function returns the date in this format: YYYY-MM-DD. so I suppose, I'm doing it right - I create date from stored string and compare it with date created from another strings.

但它不能正常工作,甚至当 column_date 的日期从今年起,并为u可以看到开始和结束日期是非常仁慈的。也尝试过这种(使用日期时间,而不是日期):

But it doesn't work, even when column_date is date from this year, and as u can see the start and end dates are very benevolent. Tried also this (used datetime instead of date):

SELECT  * FROM MyTable
    WHERE 
    (datetime(column_date) >= Date (2000-01-01) AND datetime(column_date) <= Datetime (2050-01-01))

和这个(之间,而不是与LT使用; =和> =)

and this (use between instead of <= and >=)

SELECT  * FROM MyTable
    WHERE 
    (Date(column_date) between Date (2000-01-01) AND Datetime (2050-01-01))

和所有其它可能的组合。到底我做错了,我是不是很笨,或者文件建立的谎言,还是我错过了一些很重要吗?试图找到解决办法几个小时,但没有什么工作......

and all other possible combinations. What the hell I'm doing wrong, am I stupid, or the documentaion lies, or I missed something very important? Trying to find solution few hours, but nothing works...

推荐答案

如果你是存储日期为字符串格式

if you are storing dates as strings in the format

YYYY-MM-DD HH:mm:ss  

====>那么你的日期字段是一个DateTime数据类型

====> then your date field is a DateTime datatype

因此​​,你必须使用这样的查询

Thus you have to use such query

select * 
  from MyTable 
  where mydate >= Datetime('2000-01-01 00:00:00') 
  and mydate <= Datetime('2050-01-01 23:00:59')

您还可以使用@Joop埃根给出的片段用个运营商之间是个相同的approche。

you can also use the snippet given by @Joop Eggen with th between operator it's th same approche.

在运算符的是逻辑上等同于一对比较。 X之间的Y和Z等同于X> = Y和X = Z只是介于中,x EX pression只计算一旦。看到sqlite3的文档

The BETWEEN operator is logically equivalent to a pair of comparisons. "x BETWEEN y AND z" is equivalent to "x>=y AND x<=z" except that with BETWEEN, the x expression is only evaluated once. see sqlite3 docs