1.$dateFromString字符串转时间类型
{
$dateFromString:{
dateString:<dateStringExpression>, //要转化的时间字符串
format:<formatExpression>, //转换的格式,’%Y-%m-%dT%H:%M:%S.%LZ‘
timezone:<tzExpression>, //指定时区
onError:<onErrorExpression>, //报错时输出
onNull:<onNullExpression> //null时输出
}
}
如1: {$dateFromString:{ dateString:'2017-02-16T12:16:28.787' } } 结果:ISODate('2017-02-16T12:16:28.787Z') 如2: {$dateFromString:{ dateString:'15-06-2018', fromat:'%d-%m-%Y' } } 结果:ISODate('2018-06-15T00:00:0.000Z')
2.$dateToString 日期转字符串
{$dateToString:{
dateToString:<dateExpression>,
format:<formatExpression>,
timezone:<tzExpression>,
onNull:<onNullExpression>
}
3.周、周的第XX天
MongoDB中保存的datatime类型的数据是格林尼治时间,需要转成中国的东八区的时间。格林尼治时间如:ISODate("2023-11-22T00:00:00.000Z")
①时间保存为datatime类型
如下,此处的$datas.dt是datatime类型,$isoDayOfWeek是取ISO周的第XX天
weekDay: { $isoDayOfWeek: { date: "$datas.dt", timezone: "Asia/Shanghai", }, }
②时间保存字符串类型
要先将字符串转成日期类型,再去取ISO周,如下,{"$dateFromString": {"dateString": "$data_time"}是将字符串转成日期类型,再用$isoWeek去取ISO周
isoWeek: { $isoWeek: { date: { "$dateFromString": { "dateString": "$data_time" } }, "timezone": "Asia/Shanghai" } }
4.月
注:data_time为字符串类型
month: { $substr: ['$data_time', 5, 2] }
5.年
注:data_time为字符串类型
year: { $substr: ['$data_time', 0, 4] }
6.取时段(30min和60min)
如datatime类型取时段,可先将datatime类型转成字符串,再通过字符串截取取时段
$substr: [{ $dateToString: { format: '%Y-%m-%d %H:%M:%S', date: '$num_data.dt', timezone: 'Asia/Shanghai' } }, 11, 5] 结果: 如2023-07-08T01:00:00.000Z 取时段为09:00 $substr: [{ $dateToString: { format: '%Y-%m-%d %H:%M:%S', date: '$num_data.dt', timezone: 'Asia/Shanghai' } }, 11, 2] 结果:如2023-07-08T01:00:00.000Z 取时段为09
标签:-%,dateFromString,取日,mongoDB,周月,time,字符串,timezone,data From: https://www.cnblogs.com/plzh/p/17919390.html