如何从PostgreSQL获取当日00:00-23:59的全量Unix时间戳数据?
需求与解决方案
背景
- 刚接触后端及PostgreSQL
- 前端通过
Date.now()将毫秒级Unix时间戳存入数据库,timestamp列类型为bigint - 数据库时区为
America/Los_Angeles - 需求:获取当前LA时区日期00:00:00至23:59:59的全部数据,需排除前一天22点录入的条目(如时间戳1663995295337)
最初尝试的SQL
SELECT * FROM nutrition WHERE timestamp >= (extract(epoch from now())::bigint * 1000) - 86400000 AND timestamp <= (extract(epoch from now())::bigint * 1000) + 86400000
可行解决方案
通过前端计算LA时区当天的起止时间戳,再传入SQL查询:
const today = new Date(); const beginningOfDay = today.setUTCHours(7, 0, 0, 0); // 对应LA时区00:00:00 const endOfDay = today.setUTCHours(30, 59, 59, 99); // 对应LA时区23:59:59.999 switch (method) { case "GET": try { const text = ` select * from nutrition where timestamp between ${beginningOfDay} and ${endOfDay}`; // 后续执行查询逻辑 } catch (err) { // 错误处理 }
内容的提问来源于stack exchange,提问作者Keenan
相关产品推荐
相关产品推荐

