Skip to content

uniCloud 中如何查询时间戳在本月之内的数据

【需求】

在使用 uniCloud 云开发时,需要查询创建时间在本月之内的记录。

【解决】

首先,数据中 create_date 字段存储时间戳,注意是 13 位,如果是其他位数要经过转换,否则查询结果对不上。

text
[{
    "type": 1,
    "create_date": 16828704000000, // 2503-4-14 0:0:0
    "user_id": "0ce2",
    "comment": "芭蕾舞课程到课"
},{
    "type": 1,
    "create_date": 1682872200000, // 2023-5-1 0:30:0
    "user_id": "0ce2",
    "comment": "拉丁舞课程到课"
},{   
    "type": 1,
    "create_date": 1682874000000, // 2023-5-1 1:0:0
    "user_id": "0ce2",
    "comment": "芭蕾舞课程到课"
}]

其次,使用查询语句获取数据:

text
const currentDate = new Date() // Mon May 01 2023 02:00:51 GMT+0800 (中国标准时间)
const year = currentDate.getFullYear() // 2023
const month = currentDate.getMonth() // 4
const firstDayOfMonth = new Date(year, month, 1) // Mon May 01 2023 00:00:00 GMT+0800 (中国标准时间)
const lastDayOfMonth = new Date(year, month + 1, 0) // Wed May 31 2023 00:00:00 GMT+0800 (中国标准时间)
db.collection('your-collection').where({
	user_id: '0ce2',
	create_date: db.command.gte(firstDayOfMonth.getTime()).and(db.command.lte(lastDayOfMonth
		.getTime()))
}).get()

最终结果:

text
[
    {
        "_id": "9d7d",
        "comment": "拉丁舞课程到课",
        "create_date": 1682872200000,
        "type": 1,
        "user_id": "0ce2"
    },
    {
        "_id": "eb87",
        "comment": "芭蕾舞课程到课",
        "create_date": 1682874000000,
        "type": 1,
        "user_id": "0ce2"
    }
]

编程洪同学服务平台是一个广泛收集编程相关内容和资源,旨在满足编程爱好者和专业开发人员的需求的网站。无论您是初学者还是经验丰富的开发者,都可以在这里找到有用的信息和资料,我们将助您提升编程技能和知识。
专业开发
高端定制
售后无忧
站内资源均为本站制作或收集于互联网等平台,如有侵权,请第一时间联系本站,敬请谅解!本站资源仅限于学习与参考,严禁用于各种非法活动,否则后果自行负责,本站概不承担!