du4822 2013-12-11 21:27
浏览 48
已采纳

将trunc_date postgres timestamp传递给php日期导致错误的日期

I'm using the following SQL query in postgres:

SELECT
    date_trunc('month', s.thedate),
    r.rank,
    COUNT(r.rank)
FROM
    serps s
    LEFT JOIN ranks r ON r.serpid = s.serpid
GROUP BY
   date_trunc('month', s.thedate), s.thedate, r.rank
ORDER BY
   s.thedate ASC;

when I run that query directly against the database, I get the data all the data I need and the dates seem to be correct (formatted in Y-m-d g:i:s).

However, when I run it with PHP, Postgres instead of the date returns the timestamp.

Therefore, when I use that timestamp in PHP date, the whole date is incorrect.

For instance:

The first row Postgres displays it as:

"2013-08-01 00:00:00, 36, 1"

but PHP receives:

"1375315200000, 36, 1"

When I try to do:

echo date("Y-m-d", 1375315200000);

The output is:

45552-01-02

instead of

2013-08-01

At first I thought it was a padding issue, perhaps? I dropped the last three zeros in the timestamp so:

echo date("Y-m-d", 1375315200);

and that returns:

2013-07-31

My questions are:

1) Is it only a coincidence that after dropping three zeros, the timestamp represent a day before the actual date stored in the database?

2) Why Postgres interprets the timestamp correctly; whereas php doesn't? According to the documentation Postgres timestamp should be in the unix timestamp format.

  • 写回答

1条回答 默认 最新

  • doudun1029 2013-12-11 21:37
    关注

    The number they're returning is milliseconds in the Unix era, rather than seconds. Dividing by 1000 before feeding it to PHP is necessary.

    With databases, be careful to check whether their timestamp is actually UTC/GMT, or has been offset to the server's timezone. I've seen both done. My server, located in California, is Pacific Time for MySQL timestamps. Be careful about sticking PHP timestamps into the database and then formatting with SQL, or vice-versa.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测