Format integer to formatted date in an SQLite select statement

后端 未结 3 1012
梦如初夏
梦如初夏 2020-12-19 13:08

I have an SQLite database within my Android application, which stores dates as integers. These integers are derived from a call to Java.util.Date.getTime();. I

相关标签:
3条回答
  • 2020-12-19 13:45

    The Java.util.Date.getTime(); method is returning an integer that represents the "unix time".

    The simplest way to read this number as a date is by storing it as-is, and reading it using the following Sqlite query:

    SELECT strftime('%m-%d-%Y', 1092941466, 'unixepoch');
    

    which returns:

    08-19-2004
    

    If you need another format, you can use the strftime function to format is as you like, or any of the other date formats and functions available.

    You'll have to, as Matthew Flaschen points out in a commend below, divide the date by 1000 before you are able to use them in this way. "Real" unix times are measured in seconds since the epoch, and Java.util.Date.getTime(); returns milliseconds since epoch.

    0 讨论(0)
  • 2020-12-19 13:46

    SQLite uses static rigid typing. With static typing, the datatype of a value is determined by its container - the particular column in which the value is stored.

    Any value stored in the SQLite database has one of the following storage class:

    1. NULL
    2. INTEGER
    3. REAL
    4. TEXT
    5. BLOB

    so I am not sure what you meant by but the date is stored as a long, unhelpful integer.

    For more details please refer to Datatypes In SQLite Version 3. For further information on storing date/time in SQLite please refer to SQL As Understood By SQLite.

    I hope this helps.

    0 讨论(0)
  • 2020-12-19 13:58
    SELECT strftime("%m-%d-%Y", date_col, 'unixepoch') AS date_col
    

    Your code will work if it expects a result set column in that format called date_col.

    EDIT: One thing you need to watch out for is that getTime uses milliseconds since 1970, while standard UNIX time (including SQLite) uses seconds.

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