1

I am writing an application in JavaScript (Node.js to be precise) and I currently have a date string formatted like this in a mongoose database:

2013-11-19T00:10:00-08:00

I want to run a query on the database by finding all results that have times occurring on that given day

It needs to work on all dates, not just the above example

madhead
  • 31,729
  • 16
  • 153
  • 201
user2296207
  • 171
  • 1
  • 3
  • 8

3 Answers3

1

Edit: OP changed question.

var start = new Date(2013,11,19);
var end = new Date (2013,11,20);
db.collection.find({dateTimeField: {$gte: start, $lt: end}});

Thanks to gilly3's comment on OP highlighting: http://cookbook.mongodb.org/patterns/date_range/


Maybe there's something I'm missing since you're using mongoose... but:

var dateTimeStr = '2013-11-19T00:10:00-08:00';
var dateTime = new Date(dateTimeStr);
var formatted = d.getFullYear()+'-'+(d.getMonth()+1)+'-'+d.getDate();

The date-time value you have is a standard ISO 8601 which is parsable internally by the Date object.

I'm also not sure why you have a date-time stamp stored (or being fetched) as a string. MongoDB has the ability to store a Date object.

See Where can I find documentation on formatting a date in JavaScript? for more details on formatting dates.

Community
  • 1
  • 1
zamnuts
  • 9,492
  • 3
  • 39
  • 46
  • @user2864740 the tag is nodejs and mongoose, wouldn't that hint to server-side in which case multi-browser compat isn't a problem. – zamnuts Nov 19 '13 at 18:19
  • Thanks, zamnuts. I just edited my question. I actually want to know how to query the database for all times happening on a given day. For example I want to run a query for all times occurring today. The database values are stored like this at the moment: 2013-11-19T00:10:00-08:00 – user2296207 Nov 19 '13 at 18:22
0

You can use the Windows internal command for with delims and tokens if you'd like to.

Kevin Dong
  • 5,001
  • 9
  • 29
  • 62
0
var dateTimeString = '2013-11-19T00:10:00-08:00';
// substring + indexOf solution
console.log("1)", dateTimeString.substring(0, dateTimeString.indexOf("T")));
// regex.match solution
console.log("2)", dateTimeString.match(/^\d{4}-\d{1,2}-\d{1,2}/)[0]);
Louis Ricci
  • 20,804
  • 5
  • 48
  • 62