1. 程式人生 > >Mongodb 字串轉Date 計算時間間隔

Mongodb 字串轉Date 計算時間間隔

$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得到天數