duanao3204 2019-04-27 18:08
浏览 219

在SQLite中以UTC格式存储,并使用PHP在本地时区显示

I have a table containing a datetime column:

$db = new SQLite3('test.db');
$results = $db->query('CREATE TABLE test (id INTEGER PRIMARY KEY AUTOINCREMENT,
                                                        date DATE, foo TEXT);');

and I add a row (storing the datetime of the addition of the row in UTC) with

$results = $db->query('INSERT INTO test (date, foo) VALUES(CURRENT_TIMESTAMP, "bar");');

This works. Now when displaying the rows:

$results = $db->query('SELECT * FROM test ORDER BY date desc');
while ($row = $results->fetchArray()) {
    echo $row['date'];
}

the date is displayed like this, in UTC: 2019-04-27 16:41:33.

How to display it in the local timezone instead? (including Daylight Saving)

I can imagine there are different options:

  • store directly in SQLite with local timezone (but I think this is not good practice)

  • store in SQLite in UTC, and do the UTC->local timezone conversion during the SELECT. How?

  • store in SQLite in UTC, and do the UTC->local timezone conversion via PHP.

How to do this properly?

  • 写回答

2条回答 默认 最新

  • dongpang9573 2019-04-27 19:17
    关注

    As suggested by a comment, this page mentions the localtime modifier. Here is a solution:

    $results = $db->query('SELECT datetime(date, "localtime") AS localdate, foo FROM test ORDER BY date desc');
    while ($row = $results->fetchArray()) {
        echo $row['localdate'];
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀