user2296207
user2296207

Reputation: 171

Reformat Date Regex

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

Upvotes: 1

Views: 273

Answers (3)

Louis Ricci
Louis Ricci

Reputation: 21086

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]);

Upvotes: 0

zamnuts
zamnuts

Reputation: 9592

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.

Upvotes: 1

Kevin Dong
Kevin Dong

Reputation: 5359

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

Upvotes: 0

Related Questions