How to store and get datetime value in SQLite

前端 未结 3 1517
感情败类
感情败类 2020-12-28 21:27

My table contains Birthdate field which has datatype as datetime. I want to get all records having birthday today. How can I get it?

相关标签:
3条回答
  • 2020-12-28 21:48

    SQLite has very poor support for storing dates. You can use the method suggested by Nick D above but bear in mind that this query will result in full table scan since dates are not indexed correctly in SQLite (actually SQLite does not support dates as a built-in type at all).

    If you really want to do a fast query then you'll have to add a separate (integral) column for storing the birth day (1-31) and attach an index for it in the database.

    If you only want to compare dates then you can add a single (INTEGER) column that will store the date UTC value (but this trick won't allow you to search for individual date components easily).

    Good Luck

    0 讨论(0)
  • 2020-12-28 22:06

    Try this query:

    SELECT * FROM mytable
    WHERE strftime('%m-%d', 'now') = strftime('%m-%d', birthday)
    
    0 讨论(0)
  • 2020-12-28 22:13

    Having a special datetime type has always seemed like unnecessary overhead to me, integers are fast, flexible, and use less space.

    For general datetime values use Unix Epoch timestamps. Easy to work with, extremely flexible, as well as timezone (and even calender!) agnostic. (I recently wrote an article on using them, which I really have to plug...)

    That said, if you're only interested in dates in the Gregorian calendar you may want to use a large integer in the following format: YYYYMMDD, eg 19761203. For you particular usage you could even create a four digit integer like MMDD, say 1703 — that's got to result in fast selects!

    0 讨论(0)
提交回复
热议问题