I want to find all the users created up until yesterday. This is my code to make the query string:
var today = new Date();
var a = today.getDate();
a--;
today.setDate(a);
var yesterday = today.toDateString();
and it returns something like: Sun Jan 17 2016... which IS yesterday's date, but the db stores the date in iso format like: "date" : ISODate("2016-01-13T13:23:08.419Z") so what I get is 2016-01-13T13:23:08.419Z. My problem now is that I can't use the yesterday variable to query the db for the users I need AND even if I could, I don't know how to find every registration not including the ones that took place today.
Any help? Thank you very much!
You are generating a date on the front end, and then pushing it back a day, which is totally fine for a lot of circumstances -
For this, since you are trying to find DB entries that occured, perhaps try querying the database with a timestamp ranged pulled from the ID's of each document in your database.
Here is some documentation on how to do that from mongoDB. https://docs.mongodb.org/v3.0/reference/method/ObjectId.getTimestamp/
I've also provided some additional resources that may help you figure out exactly what to query in regard to this method:
https://steveridout.github.io/mongo-object-time/
https://gist.github.com/tebemis/0e55aa0089e928f362d9
Some psuedo code:
1. Query documents in the database
2. Get a timestamp from the ID's of the documents in the database
3. Set a range of the timestamps
4. Compare returned timestamps vs a timestamp range variable (yesterdays date in this case)
5. Have the DB return only documents that are within the range
I hope this helps!
Try this, using Moment.js:
yesterday = moment().add(-1, 'days');
db.users.find({ "date": { "$lt": yesterday }});
Create a date object that represents the start of day today, use it to query your collection for documents where the date field is less than that variable, as in the following example
var start = new Date();
start.setHours(0,0,0,0);
db.users.find({ "date": { "$lt": start }});
This will look for users created up until end of day yesterday.
momentjs is a super handy utility for doing manipulations like this. Using the library, this can be achieved with the startOf() method on the moment's current date object, passing the string 'day' as arguments:
Local GMT:
var start = moment().startOf('day'); // set to 12:00 am today
db.users.find({ "date": { "$lt": start }});
For UTC:
var start = moment.utc().startOf('day');
Related
I have this string date and I want to use it in a date type for querying in sequelize.
let date = "2019-08-08T12:53:56.811Z"
let startDate = new Date(date)
console.log(startDate)
->> 2019-08-07T12:53:56.811Z
when I am trying to insert to db.it changes with another hour.
let newTask = Task.create({ time_to_deliver: startDate})
console.log(newTask.time_to_deliver)
->> 2019-08-08 17:23:56
what is this? is it something about timezone and UTC time stuff?
I think if you will make the "startDate" key in your DB of 'Date' type instead of 'String' type it will work. I have checked this with MongoDB and it worked for me.
"startDate: {type: Date}"
according to #barbsan answer . sequelize changes the date to toLocalString() format. in querying return data it turns to the actual date.
you can simply use this javascript functions for better enhancement
var d = new Date("July 21, 1983 01:15:00");
var n = d.getDate(); //this will give you 21
there is also a similar function available - getMonth(),
First, get this date day and month and time [for the time you can use these functions => 1. getTime() and 2. new Date().toISOString()]
and then send these things separately and combine them whenever you want retrieve.
There is the also second approach;
First, convert your date and time into a timestamp and enter that timestamp into the database.
var myDate="26-02-2012";
myDate=myDate.split("-");
var newDate=myDate[1]+"/"+myDate[0]+"/"+myDate[2];
alert(new Date(newDate).getTime());
I am running NodeJS 8 in AWS Lambda and want to timestamp and attach to an S3 the current day, month, year and current time when the function runs.
So if my function was running now, it would output 220619-183923 (Todays date and 6.39pm and 23 seconds in the evening.)
For something a little complex like this do I need something like MomentJS or can this be done in pure Javascript?
Eventually this will make up a S3 URL such as
https://s3.eu-west-2.amazonaws.com/mybucket.co.uk/BN-220619-183923.pdf
UPDATE
The webhook appears to have some date/time data albeit in slightly different formats that weren't outputted in the Lambda function, so these could prove useful here. Can ':' be used in a URL and could the UTC which I assume is in milliseconds be converted into my desired format?
createdDatetime=2019-06-22T18%3A20%3A42%2B00%3A00&
date=1561231242&
date_utc=1561227642&
Strangely, the date_utc value which is actually live real data. Seems to come out as 1970 here?! https://currentmillis.com/
You don't need moment. I have included a solution that is quite verbose, but is understandable. This could be shorted if needed.
Since you are using S3, you might also consider using the UTC versions of each date function (ie. .getMonth() becomes .getUTCMonth())
Adjust as needed:
createdDatetime= new Date(decodeURIComponent('2019-06-22T18%3A20%3A42%2B00%3A00'))
date=new Date(1561231242 * 1000);
date_utc=new Date(1561227642 * 1000);
console.log(createdDatetime, date, date_utc)
const theDate = createdDatetime;
const day = theDate.getUTCDate();
const month = theDate.getUTCMonth()+1;
const twoDigitMonth = month<10? "0" + month: month;
const twoDigitYear = theDate.getUTCFullYear().toString().substr(2)
const hours = theDate.getUTCHours();
const mins = theDate.getUTCMinutes();
const seconds = theDate.getUTCSeconds();
const formattedDate = `${day}${twoDigitMonth}${twoDigitYear}-${hours}${mins}${seconds}`;
console.log(formattedDate);
UPDATE based upon your update: The code here works as long as the input is a JavaScript Date object. The query parameters you provided can all be used to create the Date object.
You can definitely use MomentJS to achieve this. If you want to avoid using a large package, I use this utility function to get a readable format, see if it helps
https://gist.github.com/tstreamDOTh/b8b741853cc549f83e72572886f84479
What is the goal of creating this date string? If you just need it as a human-readable timestamp, running this would be enough:
new Date().toISOString()
That gives you the UTC time on the server. If you need the time to always be in a particular time zone, you can use moment.
I want to query mongo collection by date. Example:
var startDate = new Date(dateNow.getUTCFullYear(),dateNow.getUTCMonth(),dateNow.getUTCDate(),dateNow.getUTCHours(),0);
var endDate = new Date(dateNow.getUTCFullYear(),dateNow.getUTCMonth(),dateNow.getUTCDate(),dateNow.getUTCHours()+1,0);
query.timeRegistered = { '$gte' : startDate, '$lt' : endDate };
... make mongo query ...
But it doesn't work. I assume that is because mongo saves date object in ISODate format. This query works from shell because there mongo converts Date to ISODate but from javascript (node.js) it doesn't work. I've tried all possible solutions but neither of them helped me.
Please, if anyone has any solution I would be very gratefull....
Please consider that by default the date operation in Mongo are in UTC, e.g. I entered the record in "t1" collection at June 22nd 2015 at 7:10 PM IST. however, in the shell you can see its value as 'ISODate("2015-06-22T13:40:08.545Z")' which is 5:30 hours behind. from your javascript code (which is run on the browser and hence take the browser timezone) try to create the start and end date variables as per the UTC timezone and then query the records. Let us know if it does't work, to keep it simple, give a very large date range and see if its working or not. as I am not a JS expert, I assume you may need to adjust your dates to make it in UTC.
however, tried with the Mongo client as below and it worked so I assume from JS also it should work as long you pass the date in right timezone.
db.t1.find({dt:{$gt:ISODate("2015-06-22T13:40:00.000Z"),$lt:ISODate("2015-06-22T13:41:00.000Z")} })
I have been reading up on dates for days, seemingly going in circles here. I have a string in a DB that looks like this
2012,03,13,01,31,38
I want to create a js date object from it so...
new Date(2012,03,13,01,31,38);
Easy enough, right? But it comes back as
2012-04-13 05:31:38 +0000
So the month is off by 1 and the time is off by 4 hours (maybe DST or Timezone related???). I simply want a date that matches the one I provided. Its driving me nuts, dealing with these JS date objects.
How can I be sure the date object is the exact same date and time as the string suggests, I have no need for Timezone or DST changes, simply a date that matches a string.
More specifics regarding application:
My application for this need is for an iphone app I am developing in Titanium (which builds using JS). Basically, part of my app involves logging data and with that log I collect the device's current date and time. I save all of this information to a mySQL database. The field in the database looks like this format: "2012-02-16 00:12:32"
Here is where I start to run into problems. I am now offering the ability to edit the log, including the date and time it was logged. In order to use an iPhone "picker", I must convert the string above into a JS date object again. This usually screws things up for me. I essentially need to create a new date object with the date above, with timezone and dst being completely irrelevant, so that when I save back to the DB, its just the string above, modified as per the users request. It needs to not matter whether they are editing in pennsylvania or china, they are editing the same log date.
Sorry if this has been confusing. I am having a hard time figuring out this whole date stuff.
This depends on what your string is. If that string is UTC time, you need to parse it as that. If it's local time, you need to parse it as local time. You can make a helper method like this for that part:
function getDate(utc, year, month, day, hour, minute, second) {
if(utc) {
var utc = Date.UTC(year, month - 1, day, hour, minute, second);
return new Date(utc);
} else {
return new Date(year, month - 1, day, hour, minute, second);
}
}
Now, to parse your string, you can use this:
function fromString(utc, str) {
var parts = str.split(',');
var year = parts[0];
var month = parts[1];
var day = parts[2];
var hour = parts[3];
var minute = parts[4];
var second = parts[5];
return getDate(utc, year, month, day, hour, minute, second);
}
which you can use like this for your example:
var d = fromString(true, '2012,02,13,00,31,38'); // If UTC
var d = fromString(false, '2012,02,13,00,31,38'); // If local time
Here's a working jsFiddle that you can play with:
http://jsfiddle.net/rNqXW/
which also shows two ways to print the date (UTC or local). Hope this helps.
I had the same problem. There are two reasons for the weird time change:
Use new Date(Date.UTC(2012,03,13,01,31,38)) to avoid the time change.
Note that the month is zero based! Months go from 0 to 11 for this function.
I want to get the time difference between saved time and current time in javascript or jquery. My saved time looks like Sun Oct 24 15:55:56 GMT+05:30 2010.
The date format code in java looks like
String newDate = "2010/10/24 15:55:56";
DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = format.parse(newDate);
How to compare it with the current time and get the difference?
Is there any inbuilt function in jquery or javascript??
Any suggestions or links would be appreciative!!!
Thanks in Advance!
Update
Date is stored as varchar in the DB. I am retriving it to a String variable and then change it to java.util.Date object. The java code looks like
String newDate = "2010/10/24 15:55:56";
DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = format.parse(newDate);
This date object was sent to client. There i want to compare the saved date with current date and want to show the time difference like 2 secs ago, 2 hours ago, 2 days ago etc... like exactly in facebook. I have gone through some date to timestamp conversion tutorial in java script and now i can get the difference in timestamp. Now, i want to know how i shall change it to some format like "2 secs or 2 days or 24 hours"??. Or, how i shall change it back to date format???
Convert them into timestamps which are actually integers and can get subtracted from each other. The you just have to convert back the resulting timestamp to a javascript date object.
var diff = new Date();
diff.setTime( time2.getTime()-time1.getTime() );
You dont need to explicit convert, just do this:
var timediff = new Date() - savedTime;
This will return the difference in milliseconds.
jQuery doesn't add anything for working with dates. I'd recommend using Datejs in the event that the standard JavaScript Date API isn't sufficient.
Perhaps you could clarify exactly what input and output you're aiming for. What do you mean by "the difference?" There is more than one way to express the difference between to instants in time (primarily units and output string formatting).
Edit: since you said you're working with jQuery, how about using CuteTime? (Demo page)