當通過mongo shell來插入日期類型數據時,使用new Date()和使用Date()是不一樣的:
> db.tianyc04.insert({mark:1, mark_time:new Date()})
> db.tianyc04.insert({mark:2, mark_time:Date()})
> db.tianyc04.find()
{ "_id" : ObjectId("5126e00939899c4cf3805f9b"), "mark" : 1, "mark_time" : ISODate("2013-02-22T03:03:37.312Z") }
{ "_id" : ObjectId("5126e00c39899c4cf3805f9c"), "mark" : 2, "mark_time" : "Fri Feb 22 2013 11:03:40 GMT+0800" }
>
我們看:使用new Date(),插入的是一個isodate類型;而使用Date()插入的是一個字符串類型。
那isodate是什么日期類型的?我們看這2個值,它比字符串大概少了8小時。這是由於mongo中的date類型以UTC(Coordinated Universal Time)存儲,就等於GMT(格林尼治標准時)時間。而我當前所處的是+8區,所以mongo shell會將當前的GMT+0800時間減去8,存儲成GMT時間。
如果通過get函數來獲取,那么mongo會自動轉換成當前時區的時間:
> db.tianyc04.findOne({mark:1})
{
"_id" : ObjectId("5126e00939899c4cf3805f9b"),
"mark" : 1,
"mark_time" : ISODate("2013-02-22T03:03:37.312Z")
}
> db.tianyc04.findOne({mark:1}).mark_time
ISODate("2013-02-22T03:03:37.312Z")
> x=db.tianyc04.findOne({mark:1}).mark_time
ISODate("2013-02-22T03:03:37.312Z")
> x
ISODate("2013-02-22T03:03:37.312Z")
> x.getFullYear()
2013
> x.getMonth() # js中的月份是從0開始的(0-11)
1
> x.getMonth()+1
2
> x.getDate()
22
> x.getHours() #注意這里獲取到的小時是11,而不是3
11
> x.getMinutes()
3
> x.getSeconds()
37
ISO的日期類型可以直接使用new Date來進行比較,直接使用+8后的時間即可(注意字符串使用“/”分隔符):
> db.tianyc04.find({mark_time:{$gt: new Date('2013/02/22 11:03:37')}})
{ "_id" : ObjectId("5126e00939899c4cf3805f9b"), "mark" : 1, "mark_time" : ISODate("2013-02-22T03:03:37.312Z") }
> db.tianyc04.find({mark_time:{$lt: new Date('2013/02/22 11:03:37')}})
> db.tianyc04.find({mark_time:{$lt: new Date('2013/02/22 11:03:38')}})
{ "_id" : ObjectId("5126e00939899c4cf3805f9b"), "mark" : 1, "mark_time" : ISODate("2013-02-22T03:03:37.312Z") }
> db.tianyc04.find({mark_time:{$gt: new Date('2013/02/22 11:03:37'), $lt: new Date('2013/02/22 11:03:38')}})
{ "_id" : ObjectId("5126e00939899c4cf3805f9b"), "mark" : 1, "mark_time" : ISODate("2013-02-22T03:03:37.312Z") }
那么,如果使用python來讀取isodate類型的數據,會自動轉化為GMT+0800時間嗎?我繼續測試:
> exit
bye
C:\>python
'import site' failed; use -v for traceback
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Int
Type "help", "copyright", "credits" or "license" for more information.
>>> import pymongo
>>> conn=pymongo.Connection('10.0.0.35',20000)
>>> db=conn.test
>>> tianyc04=db.tianyc04.find()
#我們看,從python取出來的也是一個日期類型,一個字符串類型
>>> print tianyc04[0]
{u'mark_time': datetime.datetime(2013, 2, 2, 1, 52, 12, 281000), u'_id': ObjectId('510c714c045d7d8d7b6ec1bb'), u'mark': 1.0}
>>> print tianyc04[1]
{u'mark_time': u'Sat Feb 02 2013 09:52:17 GMT+0800', u'_id': ObjectId('510c7151045d7d8d7b6ec1bc'), u'mark': 1.0}
#我打印出mongo的isodate類型,發現並沒有自動轉換為GMT+0800時間:
>>> print tianyc04[0]['mark_time']
2013-02-02 01:52:12.281000
>>> print tianyc04[1]['mark_time']
Sat Feb 02 2013 09:52:17 GMT+0800