SQLite compare dates

前端 未结 3 801
误落风尘
误落风尘 2020-12-05 15:53

I have this SQL-Statement:

SELECT Geburtsdatum FROM Kunde
WHERE Geburtsdatum BETWEEN \'1993-01-01\' AND \'2000-01-01\'

but I get some weird

相关标签:
3条回答
  • 2020-12-05 16:06

    Someone had the same problem and got it resolved. (use datetime function before comparison)

    See SQLite DateTime comparison

    Excerpt: Following the datetime function and having a string format as YYYY-MM-DD HH:mm:ss i achieved good results as follows

    select * 
      from table_1 
      where mydate >= Datetime('2009-11-13 00:00:00') 
      and mydate <= Datetime('2009-11-15 00:00:00')
    

    --EDIT--

    You are basically comparing strings. Which is why the unexpected behavior. Convert to datetime using the function right before comparison and it should work.

    0 讨论(0)
  • 2020-12-05 16:20

    To be able to compare dates, you must store them in one of SQLite's supported date formats, such as a JJJJ-MM-TT string. Your dates are stored as strings in a localized date format which is not recognized by SQLite.

    If the most significant field is not at the start of the string, string comparisons will not work for dates.
    With the values currently in your table, you will not be able to do any comparisons.

    0 讨论(0)
  • 2020-12-05 16:30

    From the documentation:

    SQLite does not have a storage class set aside for storing dates and/or times.

    So your column isn't exactly stored as a date. Reading further, we learn that columns specifed as DATE are actually stored as NUMERIC using affinity rule 5.

    Going back up to section 1.2:

    REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.

    Good. So let's try:

    SELECT Geburtsdatum FROM Kunde
    WHERE Geburtsdatum 
        BETWEEN julianday('1993-01-01') AND julianday('2000-01-01'); 
    

    Oddly enough, SQL Fiddle seems to store DATEs as strings and the above doesn't work. In this case, the following should:

    SELECT Geburtsdatum FROM Kunde
    WHERE date(Geburtsdatum)
        BETWEEN date('1993-01-01') AND date('2000-01-01'); 
    

    Additionally, in your case you seem to be getting some strange (read: localized) format returned. I wonder if it really is a string in your case too, just with a different format. You could try:

    SELECT Geburtsdatum FROM Kunde
    WHERE strftime('%d.%m.%Y', Geburtsdatum)
        BETWEEN date('1993-01-01') AND date('2000-01-01'); 
    
    0 讨论(0)
提交回复
热议问题