如何使用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
相关产品推荐
相关产品推荐

