Mongodb-字符串转时间-计算时间间隔

29次阅读

共计 564 个字符,预计需要花费 2 分钟才能阅读完成。

$dateFromString: {
  dateString: '2019-07-22',
  timezone: 'Asia/Shanghai'
}}

确定好字符串和时区即可

计算时间间隔

$subtract:[
    {$dateFromString: {
            dateString: '2019-07-22',
            timezone: 'Asia/Shanghai'
        }}, 
        {$dateFromString: {
            dateString: '$time',
            timezone: 'Asia/Shanghai'
        }}
        
    ]
}

计算间隔多少天

db.col.aggregate([{
    $project: {
        title: 2,
        likes: 1,
        startDay: "$time",
        endDay: new ISODate('2019-07-22 00:00:00'),
        days: {
            $floor:{
                $divide:[
                    {$subtract:[
                        {$dateFromString: {
                                dateString: '2019-07-22',
                                timezone: 'Asia/Shanghai'
                            }}, 
                            {$dateFromString: {
                                dateString: '$time',
                                timezone: 'Asia/Shanghai'
                            }}
                            
                        ]
                    }, 60 * 60 * 24 * 1000
                ]
             }
         }
    }
}])

时间相减然后得到时间戳,除以 60 60 24 * 1000 得到天数,最后取整即可

正文完
 0