I am trying to query all records from today but I get nothing, so My question is:
How to query with date validations in TypeORM?
My code:
all = await connection
.createQueryBuilder(Earnings, 't0')
.addSelect('t3.id', 't3_id')
.addSelect('t3.UID', 't3_UID')
.addSelect('t3.name', 't3_name')
.addSelect('t3.chips', 't3_chips')
.addSelect('t3.tickets', 't3_tickets')
.addSelect('t3.masteredLevel', 't3_masteredLevel')
.addSelect('t2.UID', 't2_UID')
.addSelect('t2.name', 't2_name')
.addSelect('t2.rule', 't2_rule')
.addSelect('t1.id', 't1_id')
.innerJoin(Questions, 't1', 't0.questionID = t1.id')
.innerJoin(Lessons, 't2', 't1.lessonUID = t2.UID')
.innerJoin(Topics, 't3', 't2.topicUID = t3.UID')
.where('t0.challenge = 1')
.andWhere('t0.createdAt = :today')
.andWhere('t0.userID = :userID')
.setParameters({ userID: user.id })
.setParameters({ today: moment() })
.getRawMany()
Your .andWhere('t0.createdAt = :today') only selects rows created at the instant of today parameter. You have set this parameter as moment(), which is not a date.
Since we can safely assume no rows will be created in the future, your simplest solution here is: .andWhere('t0.createdAt >= :today'), which selects rows created AFTER 00:00 today.
You can combine the addWhere and setParameters into one:
.andWhere('t0.createdAt >= :today', { today: moment().toDate() }) // note moment.toDate()
Alternatively use the MySql CURDATE() function to get the current date:
.andWhere('t0.createdAt >= CURDATE()')
When you test this, I recommend that you turn on TypeOrm full logging so you can see the actual generated SQL and you will be able to quickly solve any problems. See TypeOrm logging.
For TypeORM + PSQL
Sort items by today's date
.andWhere('t0.createdAt >= CURRENT_DATE')
I want to get the current date and time from the firebase. Applying the following code while console logged I got the date of 1970. How to get the current date and time?
Edited Code after getting solution
let current_date;
firebase.database().ref("/.info/serverTimeOffset").on('value', function(offset) {
current_date = new Date(Date.now() + offset.val());
current_date.toString();
});
console.log(current_date);
use below line
Date.now() + offset.val()
Then the code look like below
firebase.database().ref("/.info/serverTimeOffset").on('value', function(offset) {
var date = new Date(Date.now() + offset.val());
console.log(date.toString());
});
offset.val() does not give the current UNIX epoch. It tells you how many milliseconds the client's clock is from the Firebase server clock. In most cases this will be very small (~100ms), hence your issue.
To get current date:
firebase.database().ref("/.info/serverTimeOffset").on('value', function(offset) {
var date = Date.now() + offset.val();
console.log(date);
});
I am trying to create a timer with Javascript but I don't know how to add one second to a time string.
Time string: 03:31:15
function updateWorked() {
var time = $("#worked").html();
???
$("#worked").html(wtime);
}
$(document).ready(function() {
setInterval('updateWorked()', 1000);
});
What should I write in "???" to make this work?
Assuming you are using something like PHP to get the time string in the first place, and you can't keep track of the date/time as a number as suggested by Marc B, you can parse the string yourself like this:
var $worked = $("#worked");
var myTime = $worked.html();
var ss = myTime.split(":");
var dt = new Date();
dt.setHours(ss[0]);
dt.setMinutes(ss[1]);
dt.setSeconds(ss[2]);
var dt2 = new Date(dt.valueOf() + 1000);
var ts = dt2.toTimeString().split(" ")[0];
$worked.html(ts);
Edit: Working jsFiddle here of this code.
Here's the code with a timer: jsFiddle
Below is an example on how to add a second to a time string. You can use the date object to print out the string in any format that you would like, in this example i'm just using the build in toTimeString method.
var timeString = "10/09/2012 14:41:08";
// start time
var startTime = new Date(timeString);
// prints 14:41:08 GMT-0400 (EDT)
console.log(startTime.toTimeString())
// add a second to the start time
startTime.setSeconds(startTime.getSeconds() + 1);
// prints 14:41:09 GMT-0400 (EDT)
console.log(startTime.toTimeString())
If you're trying to keep a counter in real time, you should use new Date() to get the time, and then format it:
function updateWorked() {
var time = new Date(),
wtime = formatDate(time);
$("#worked").html(wtime);
}
However, if you're trying to keep a specific time, then you should up-scope a Date object and use that:
var time = new Date(/* your starting time */);
function updateWorked() {
time.setTime(time.getTime()+1000);
var wtime = formatDate(time);
$("#worked").html(wtime);
}
Also, you'd want to add a formatDate function:
function formatDate(date) {
var hours = date.getHours().toString();
if (hours.length < 2) hours = '0'+hours;
var minutes = date.getMinutes().toString();
if (minutes.length < 2) minutes = '0'+minutes;
var seconds = date.getSeconds().toString();
if (seconds.length < 2) seconds = '0'+seconds;
return hours+':'+minutes+':'+seconds;
}
Using mixture of jquery and javascript you can achieve this example.
I tired to achive what you looking for, first created a date object and get all the values of time, minute and second and then replaced the value.
Please have a look at jsfiddle
DEMO
http://jsfiddle.net/saorabhkr/xtrpK/
I'm trying to use jquery countdown to sync with the server so the time is the same for all visitors. The files are being hosted on AppEngine using the static settings to host the HTML. PHP doesn't work on AppEngine.
Would it be possible to sync with the server time using Python under AppEngine's static settings? - how would I use datetime.now() in Jquery?
function countdown() {
var eventTime = new Date('May 23, 2012 08:00:00');
$('#time-left').countdown({ until: eventTime, layout: '<ul class="timer"><li class="days">{dn}</li> <li class="hours">{hnn}</li><li class="mins">{mnn}</li><li class="secs">{snn}</li></ul>',
serverSync: function() { return new Date('datetime.now()') }});
}
Thanks for your help.
its difficult to calculate time in client side because its vary in different time zones.... so get the server time in UTC and create a local time variable in UTC offset, then compare sec deff in local time
// return string must be in UTC time yyyy/MM/dd H:mm:ss format in Json result
$.get("timerequestmethod", function (data) {
var dateArray = data.split(' ');
var seconds = getSeconds(dateArray);
// create countdown until 'seconds' declare in above statement
});
getSeconds = (function (dateArray) {
var dt = dateArray[0].split('/');
var tm = dateArray[1].split(':');
var times = new Date();
times.setUTCFullYear(dt[0], (dt[1] > 0 ? dt[1] - 1 : dt[1]), dt[2]);
times.setUTCHours(tm[0]);
times.setUTCMinutes(tm[1]);
times.setUTCSeconds(tm[2]);
return (times - new Date()) / 1000;
});
I know that ObjectIds contain the date they were created on. Is there a way to query this aspect of the ObjectId?
Popping Timestamps into ObjectIds covers queries based on dates embedded in the ObjectId in great detail.
Briefly in JavaScript code:
/* This function returns an ObjectId embedded with a given datetime */
/* Accepts both Date object and string input */
function objectIdWithTimestamp(timestamp) {
/* Convert string date to Date object (otherwise assume timestamp is a date) */
if (typeof(timestamp) == 'string') {
timestamp = new Date(timestamp);
}
/* Convert date object to hex seconds since Unix epoch */
var hexSeconds = Math.floor(timestamp/1000).toString(16);
/* Create an ObjectId with that hex timestamp */
var constructedObjectId = ObjectId(hexSeconds + "0000000000000000");
return constructedObjectId
}
/* Find all documents created after midnight on May 25th, 1980 */
db.mycollection.find({ _id: { $gt: objectIdWithTimestamp('1980/05/25') } });
In pymongo, it can be done this way:
import datetime
from bson.objectid import ObjectId
mins = 15
gen_time = datetime.datetime.today() - datetime.timedelta(mins=mins)
dummy_id = ObjectId.from_datetime(gen_time)
result = list(db.coll.find({"_id": {"$gte": dummy_id}}))
Using inbuilt function provided by mongodb drivers in in Node.js lets you query by any timestamp:
var timestamp = Date.now();
var objectId = ObjectID.createFromTime(timestamp / 1000);
Alternatively, to search for records before the current time, you can simply do:
var objectId = new ObjectID(); // or ObjectId in the mongo shell
Source: http://mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html
You can use $convert function to extract the date from ObjectId starting in 4.0 version.
Something like
$convert: { input: "$_id", to: "date" }
You can query on date comparing between start and end time for date.
db.collectionname.find({
"$expr":{
"$and":[
{"$gte":[{"$convert":{"input":"$_id","to":"date"}}, ISODate("2018-07-03T00:00:00.000Z")]},
{"$lte":[{"$convert":{"input":"$_id","to":"date"}}, ISODate("2018-07-03T11:59:59.999Z")]}
]
}
})
OR
You can use shorthand $toDate to achieve the same.
db.collectionname.find({
"$expr":{
"$and":[
{"$gte":[{"$toDate":"$_id"}, ISODate("2018-07-03T00:00:00.000Z")]},
{"$lte":[{"$toDate":"$_id"},ISODate("2018-07-03T11:59:59.999Z")]}
]
}
})
how to find Find the Command (this date[2015-1-12] to this Date[2015-1-15]):
db.collection.find({
_id: {
$gt: ObjectId(Math.floor((new Date('2015/1/12'))/1000).toString(16) + "0000000000000000"),
$lt: ObjectId(Math.floor((new Date('2015/1/15'))/1000).toString(16) + "0000000000000000")
}
}).pretty()
Count the Command (this date[2015-1-12] to this Date[2015-1-15]):
db.collection.count({
_id: {
$gt: ObjectId(Math.floor((new Date('2015/1/12'))/1000).toString(16) + "0000000000000000"),
$lt: ObjectId(Math.floor((new Date('2015/1/15'))/1000).toString(16) + "0000000000000000")
}
})
Remove the Command (this date[2015-1-12] to this Date[2015-1-15]):
db.collection.remove({
_id: {
$gt: ObjectId(Math.floor((new Date('2015/1/12'))/1000).toString(16) + "0000000000000000"),
$lt: ObjectId(Math.floor((new Date('2015/1/15'))/1000).toString(16) + "0000000000000000")
}
})
Since the first 4 bytes of an ObjectId represent a timestamp, to query your collection chronologically, simply order by id:
# oldest first; use pymongo.DESCENDING for most recent first
items = db.your_collection.find().sort("_id", pymongo.ASCENDING)
After you get the documents, you can get the ObjectId's generation time like so:
id = some_object_id
generation_time = id.generation_time
Yes you can query object by date using MongoDB inserted ID
db.collectionname.find({_id: {$lt: ObjectId.fromDate( new ISODate("TZformat") ) } });
let's suppose users is my collection and I want all users created less than 05 January 2018
db.users.find({_id: {$lt: ObjectId.fromDate( new ISODate("2018-01-05T00:00:00.000Z") ) } });
For running from a query we can use like
db.users.find({_id: {$lt: ObjectId.fromDate(new Date((new Date().getTime() - (1 * 3 * 60 * 60 * 1000))) ) } })
All the users from the current time - 3 hours
To get last 60 days old documents in mongo collection i used below query in shell.
db.collection.find({_id: {$lt:new ObjectId( Math.floor(new Date(new Date()-1000*60*60*24*60).getTime()/1000).toString(16) + "0000000000000000" )}})
If you want to make a range query, you can do it like in this post. For example querying for a specific day (i.e. Apr 4th 2015):
> var objIdMin = ObjectId(Math.floor((new Date('2015/4/4'))/1000).toString(16) + "0000000000000000")
> var objIdMax = ObjectId(Math.floor((new Date('2015/4/5'))/1000).toString(16) + "0000000000000000")
> db.collection.find({_id:{$gt: objIdMin, $lt: objIdMax}}).pretty()
From the documentation:
o = new ObjectId()
date = o.getTimestamp()
this way you have date that is a ISODate.
Look at
http://www.mongodb.org/display/DOCS/Optimizing+Object+IDs#OptimizingObjectIDs-Extractinsertiontimesfromidratherthanhavingaseparatetimestampfield.
for more information
Using MongoObjectID you should also find results as given below
db.mycollection.find({ _id: { $gt: ObjectId("5217a543dd99a6d9e0f74702").getTimestamp().getTime()}});
A Solution Filtering within MongoDB Compass.
Based on versions:
Compass version: 1.25.0
MongoDB version: 4.2.8
Option 1:
#s7vr 's answer worked perfectly for me. You can paste this into the Filter field:
{$expr: { $and: [ {$gte: [{$toDate: "$_id"}, ISODate('2021-01-01')]}, {$lt: [{$toDate: "$_id"}, ISODate('2021-02-01')]} ] } }
Option 2:
I also found this to work (remember that the Date's month parameter is 0-based indexing so January is 0):
{_id: {$gte: ObjectId(Date(2021, 0, 1) / 1000), $lt: ObjectId(Date(2021, 1, 1) / 1000) } }
Option 3:
Equivalent with ISODate:
{_id: {$gte: ObjectId(ISODate('2021-01-01') / 1000), $lt: ObjectId(Date('2021-02-01') / 1000) } }
After writing this post, I decided to run the Explain on these queries. Here's the skinny on performance:
Option 1: 39 ms, 0 indexes used, 30 ms in COLLSCAN
Option 2: 0 ms, _id index used
Option 3: 1 ms, _id index used, 1 ms in FETCH
Based on my rudimentary analysis, it appears that option 2 is the most efficient. I will use Option 3, personally, as it is a little cleaner to use ISODate rather than remembering 0-based month indexing in the Date object.
In rails mongoid you can query using
time = Time.utc(2010, 1, 1)
time_id = ObjectId.from_time(time)
collection.find({'_id' => {'$lt' => time_id}})