【问题标题】:Postgresql datetime resolution of milliseconds compatible with Javascript Date与 Javascript Date 兼容的 Postgresql datetime 毫秒分辨率
【发布时间】:2021-11-21 06:28:48
【问题描述】:

我在 Supabase 的 PostgreSQL (13.3) 表中有一个时间戳列。它目前将时间戳存储到微秒分辨率。我想将时间戳发送到一个 javascript 客户端,并使用它们来查询(通过 Supabase)通过这个时间戳值精确匹配的行。 Javascript Date 对象丢弃微秒并且只存储毫秒。我可以将微秒字符串与 Date 对象(我需要在各种 UI 组件中呈现)一起存储在 javascript 客户端中,但这似乎不必要地混乱且容易出错,因为重复的数据可能会不同步。

是否可以强制在 PostgreSQL 中创建的时间戳值始终为毫秒而不是微秒分辨率?目前我在 CREATE TABLE 和 upsert 函数中使用以下内容:

CREATE TABLE abc (
  -- other fields
  modified_at timestamp without time zone DEFAULT now()::timestamp(3) NOT NULL
);
  UPDATE abc
  SET
    -- other fields
    modified_at = now()::timestamp(3)
  WHERE modified_at = item.modified_at;

this question相关。

【问题讨论】:

    标签: javascript postgresql datetime timestamp


    【解决方案1】:

    Timestamp 接受要保留的小数位数的参数,以便您可以使用以下方式定义表格:

    modified_at timestamp(3) without time zone DEFAULT now() NOT NULL
    

    这意味着它将始终具有 000 微秒,这将始终与 Javascript 的 Date 对象一起使用。

    【讨论】:

      【解决方案2】:

      如果你愿意,你可以使用CREATE DOMAIN:

      create domain js_ts timestamptz(3);
      create table js_tz_test(id int, ts_fld js_ts);
      
      \d js_tz_test
      Table "public.js_tz_test"
       Column |  Type   | Collation | Nullable | Default 
      --------+---------+-----------+----------+---------
       id     | integer |           |          | 
       ts_fld | js_ts   |        
      
      insert into js_tz_test values (1, now());
      
      select * from js_tz_test ;
       id |           ts_fld           
      ----+----------------------------
        1 | 2021-09-29 09:00:45.626-07
      
      select now()::js_ts;
                  now             
      ----------------------------
       2021-09-29 09:04:55.388-07
      
      
      

      【讨论】:

        猜你喜欢
        • 2012-11-12
        • 2011-11-06
        • 1970-01-01
        • 2018-06-01
        • 2014-09-08
        • 1970-01-01
        • 1970-01-01
        • 2020-02-06
        • 1970-01-01
        相关资源
        最近更新 更多