Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

mongodb - How to deal with the timezone issue when storing dates in utc using mongod?

I have a mongodb collection where each document has some attributes and a utc timestamp. I need to pull out data from the collection and use the aggregation framework because I use the data from the collection to display some charts on the user interface. However, I need to do the aggregation as per the user's timezone. Assuming I know the user's timezone(passed in the request from browser or in some other manner), is there any way to use the aggregation framework to aggregate based on the [client's] timezone?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Aside from the SERVER-6310 mentioned by Matt Johnson, one other workaround is to use the $project operator to add or subtract from the UTC time zone to "shift the time" into the correct local zone. Turns out you can add or subtract time in milliseconds.

For example, assuming I have a Date field called orderTime. I'd like to query for EDT. That is -4 hours from UTC. That's 4 * 60 * 60 * 1000 milliseconds.

So I would then write the following projection to get day_ordered in local time for all my records:

db.table.aggregate( 
    { $project : { orderTimeLocal : { $subtract : [ "$orderTime", 14400000] } } },
    { $project : { day_ordered : { $dayOfYear : "$orderTimeLocal" } } })

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...