模式切换
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"
}
]