You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Knex查询updated字段大于指定时间戳的所有记录

问题原因

  • 表名不匹配:创建的表为product_name,查询代码中传入的table.trackings为错误表名,会直接导致查询范围错误。
  • 时区格式不兼容:输入参数是带UTC标识的ISO时间字符串,而MySQL的datetime类型不存储时区信息,默认以数据库实例的本地时区存储时间,直接比对两类格式的字符串会因为时区差出现逻辑错误。

正确实现方案

方案1:手动转换时间格式(适合数据库时区统一为UTC的场景)

先把输入的UTC格式时间转换为MySQL支持的YYYY-MM-DD HH:mm:ss格式再执行查询:

// 转换ISO时间为MySQL datetime兼容格式
const formattedInput = new Date(input).toISOString().slice(0, 19).replace('T', ' ')
const results = await kx('product_name') // 替换为正确的表名
  .select()
  .where('updated', '>', formattedInput)

方案2:用knex raw自动处理类型转换(更稳妥,避免手动时区处理错误)

通过参数绑定让knex自动完成时间类型和时区的适配:

const results = await kx('product_name')
  .select()
  .whereRaw('?? > ?', ['updated', new Date(input)])

方案3:数据库使用非UTC时区的场景

如果数据库用的是中国标准时间(东八区),可以借助时间库转换时区后查询,示例用dayjs实现:

const dayjs = require('dayjs')
const utc = require('dayjs/plugin/utc')
const timezone = require('dayjs/plugin/timezone')
dayjs.extend(utc)
dayjs.extend(timezone)

// 转换为东八区时间格式
const formattedInput = dayjs(input).tz('Asia/Shanghai').format('YYYY-MM-DD HH:mm:ss')
const results = await kx('product_name')
  .select()
  .where('updated', '>', formattedInput)

内容的提问来源于stack exchange,提问作者angry kiwi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 10:45:01