Sqlite: CURRENT_TIMESTAMP is in GMT, not the timezone of the machine

后端 未结 11 830
小蘑菇
小蘑菇 2020-11-29 16:36

I have a sqlite (v3) table with this column definition:

\"timestamp\" DATETIME DEFAULT CURRENT_TIMESTAMP

The server that this database live

相关标签:
11条回答
  • 2020-11-29 16:58
    SELECT datetime('now', 'localtime');
    
    0 讨论(0)
  • 2020-11-29 17:04

    I think this might help.

    SELECT datetime(strftime('%s','now'), 'unixepoch', 'localtime');
    
    0 讨论(0)
  • 2020-11-29 17:05

    You should, as a rule, leave timestamps in the database in GMT, and only convert them to/from local time on input/output, when you can convert them to the user's (not server's) local timestamp.

    It would be nice if you could do the following:

    SELECT DATETIME(col, 'PDT')
    

    ...to output the timestamp for a user on Pacific Daylight Time. Unfortunately, that doesn't work. According to this SQLite tutorial, however (scroll down to "Other Date and Time Commands"), you can ask for the time, and then apply an offset (in hours) at the same time. So, if you do know the user's timezone offset, you're good.

    Doesn't deal with daylight saving rules, though...

    0 讨论(0)
  • 2020-11-29 17:06

    I found on the sqlite documentation (https://www.sqlite.org/lang_datefunc.html) this text:

    Compute the date and time given a unix timestamp 1092941466, and compensate for your local timezone.

    SELECT datetime(1092941466, 'unixepoch', 'localtime');
    

    That didn't look like it fit my needs, so I tried changing the "datetime" function around a bit, and wound up with this:

    select datetime(timestamp, 'localtime')
    

    That seems to work - is that the correct way to convert for your timezone, or is there a better way to do this?

    0 讨论(0)
  • 2020-11-29 17:06

    simply use local time as the default:

    CREATE TABLE whatever(
         ....
         timestamp DATE DEFAULT (datetime('now','localtime')),
         ...
    );
    
    0 讨论(0)
提交回复
热议问题