Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return documents created since midnight

I want to find all document's created since midnight, regardless of the users timezone. If the users on Pacific time, it should show all their documents since midnight Pacific. Same with Eastern time.

I'm on Eastern time and this works for me:

var d = new Date();
    var midnight = d.setHours(0,0,0,0); // last midnight

    var count = Items.find({
      username: Meteor.user().username,
      createdAt: { $gt: midnight }
    }).count();

But my client is on CST and it doesn't work for him. It instead shows documents created since like 10pm or 11pm CST the previous day. So this seems like a timezone issue for me.

like image 544
stephenthedev Avatar asked Mar 27 '15 00:03

stephenthedev


People also ask

What is ISO date in MongoDB?

ISODate("2012-12-19T06:01:17.171Z") ISODate() is a helper function that's built into to MongoDB and wraps the native JavaScript Date object. When you use the ISODate() constructor from the Mongo shell, it actually returns a JavaScript Date object.

Is not equal to MongoDB?

MongoDB provides different types of comparison operators and inequality or not equals operator( $ne ) is one of them. This operator is used to select those documents where the value of the field does not equal to the given value. It also includes those documents that do not contain the specified field.

How do I change the date format in MongoDB?

You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.


1 Answers

Assuming that this is a client-side issue only (all of the times are stored in UTC on the server) then you can get the UTC adjusted time for midnight of the users current timezone by doing the following:

var now = new Date();
var midnight = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var midnight_utc = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()));

See this fiddle: https://jsfiddle.net/Lbk1vo0j/1/ For example, for my current time zone (eastern) I get the following values for now, midnight, and midnight_utc (when printing the Date objects using the toLocaleString() method):

3/30/2015, 3:06:39 PM
3/30/2015, 12:00:00 AM
3/29/2015, 8:00:00 PM
like image 114
InPursuit Avatar answered Nov 01 '22 06:11

InPursuit