Query by date and time only, without year using SQLite - javascript

I am storing birthdays in my SQLite database, they are dates converted to my own timezone from another timezone, every hour I want to query my database to get the dates that are the same day and hour
// Stored in DB:
const date = parseFromTimeZone(`2020-${bdayReply} 13:42:00`, { timeZone });
// Query
const birthday = await Birthday.findOne({ where: { date: new Date() } });
// Generated query
query: SELECT "Birthday"."id" AS "Birthday_id", "Birthday"."userId" AS "Birthday_userId", "Birthday"."date" AS "Birthday_date", "Birthday"."birthdayConfigGuildId" AS "Birthday_birthdayConfigGuildId" FROM "birthday" "Birthday" WHERE "Birthday"."date" = ? LIMIT 1 -- PARAMETERS: ["2020-02-03T07:42:00.005Z"]
// Output of new Date() at the time of running the query
2020-02-03T07:42:00.023Z
// Example of record active in my DB at that point (date var from earlier)
2020-02-03 07:42:00.000
The ORM I'm using allows for raw queries as well, now I was wondering what my query should look like to return the above record in the example, or maybe I can use a date library like date-fns to convert the new Date() to match the format of the database, what would that look like?

If you want to use an SQL raw query, it should looks like this :
SELECT * FROM my_table WHERE MONTH(my_date) = MONTH(NOW()) AND DAY(my_date) = DAY(NOW())
In SQLite, the syntax is :
SELECT * FROM my_table WHERE strftime('%m',my_date) = strftime('%m','now') AND strftime('%d',my_date) = strftime('%d','now')

Related

Can't convert timestamp to date properly in Javascript

I use mongodb as my database and in that db I have a timestamp field but I haven't seen any format similar to that. Some of them are:
1657479170.7300725
1657479170.7301126
1657479170.7301197
1657479170.9120467
1657479170.932398
When i try to convert this to normal date format (YYYY-MM-DD) I get the correct date. For example the converted date of the first timestamp above is:
10.07.2022 21:52:50
However when I try to convert it in javascript I get:
1970-01-20 06:24:39
which is definitely not correct value.
My code for the conversion :
ConvH.forEach(conv => {
conv.tracker.events.forEach(element => {
console.log(parseFloat( parseFloat(element.timestamp.toFixed(4))), moment(new Date( parseFloat( element.timestamp.toFixed(4)))).format("YYYY-MM-DD HH:mm:ss"));
element.timestamp = new Date(element.timestamp).toLocaleString();
})
});
Note : new Date(element.timestamp).toLocaleString(); gives the same thing :/
Try this: new Date(timestamp.getHighBits() * 1000)

TypeORM query all records from today

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')

Convert given timestamp to influxdb timestamp

My Incoming Date is in format : 15.08.2017 23:03:23.120000
Here I am using Node-Red Platform to convert msg.payload.time in Influx timestamp but I am getting this Error:
"Error: Expected numeric value for, timestamp, but got '15.08.2017 23:03:23.120000'!".
Please let me know the script for given timestamp to influxdb timestamp.
InfluxDB expects unix timestamps and msg.payload.time might be a string, hence you are getting the error.
In order to generate a timeStamp from a date, you can use the Date functionality of JS.
It works in the following way:
new Date('<your-date-string>').valueOf()
Here the date-string is expected in 'YYYY-MM-DD hh:mm:ssZ' format.
In your case, since the msg.payload.time is available in dd.mm.yy hh:mm:ssZ format, you will need to perform some additional operations.
You can update your code as below:
const incomingDate = msg.payload.time;
// extract the date dd.mm.yyyy from the incoming Date String
const splittedDate = incomingDate.split(' ');
// Convert the date from dd.mm.yyyy to yyyy-mm-dd format
let date = splittedDate[0].split('.').reverse().join('-');
// Store time value in a separate variable for later use.
const time = splittedDate[1];
// merge date and time to form yyyy-mm-dd hh:mm:ssZ format
const datetime = `${date} ${time}`
// assign the timestamp value to fields.time
fields.time = new Date(datetime).valueOf();
Here is a working example
const incomingDate = '15.08.2017 23:03:23.120000';
const splittedDate = incomingDate.split(' ');
let date = splittedDate[0].split('.').reverse().join('-');
const time = splittedDate[1];
const datetime = `${date} ${time}`
console.log(datetime);
console.log(new Date(datetime).valueOf())

Querying a timestamp by date with Sequelize

I want to find some entries in my DB through the createdAt column, but just using the date. I am using postgres and the createdAt is a timestamptz. Here is an example of what an entry in it looks like: 2019-02-27 20:17:07.05+00
This is what the setting of my query looks like:
const dateString = momentDate.format('YYYY-MM-DD')
query.createdAt = { $iLike: `%${dateString}` }
Unfortunately this is not working and I am getting the following error:
retry-as-promised:error SequelizeDatabaseError: operator does not exist: timestamp with time zone ~~* unknown
Is the issue perhaps because I am using a string? What is the right way to query by date?
Using function DateDiff to get days from between createdAt and dateString. Need to cast dateString to datetime
var sequelize = require('sequelize');
var dateString = '01/03/2019';
yourModel.findAll({
where: sequelize.literal(`DATEDIFF(day,Cast(${dateString} as datetime), createdAt) = 0`)
})
.then(results => {
})
.catch(err => {
});

Problems in setting a date constraint on a parse query

I'm trying to make a parse query and put a date constraint on the query via javascript API.
This is the Result table/object (on parse.com) which I'm making a query for:
Column Data type
objectId String
createdDate Date
updatedAt Date
obtainedPonts Number
relatedDriver Relation
relatedTest Relation
ACL ACL
resultCeasesToBeValid Date
didPassTheTest Boolean
Some example data from resultCeasesToBeValid:
This is my goal: I want the query to give me a set of Result where today < resultCeasesToBeValid.
My problem is that I always recieve an Result array with .length = 0 when I'm trying to put date constraints on the query.
function IsApprovedAndHasValidResults(currentDriverObjectId) {
var Driver = Parse.Object.extend('Driver');
var currentDriverObject = new Driver();
currentDriverObject.id = currentDriverObjectId;
var queryResult = new Parse.Query(Result);
//set the constraints
queryResult.equalTo('relatedDriver', currentDriverObject); //this constraint works as expected
/****************************************************************************************************
*var today = new Date(); // "today" is as time of writing 3 oct 2014 *
* *
* //will give me a parseResults[] of .length=0: *
*queryResult.lessThan('resultCeasesToBeValid', today); *
* *
* //will give me a parseResults[] of .length=0: *
*queryResult.lessThan('resultCeasesToBeValid', { "__type": "Date", "iso": today.toISOString() }); *
* *
*****************************************************************************************************/
queryResult.find({
success: function (parseResults) {
// results is an array of Parse.Object.
/*when the code gets here parseResults array.lenght equals 0*/
},
error: function (error) {
// error is an instance of Parse.Error.
/*will never be here*/
}
});
}
Other developers seem to have the same problem, user Abhishek suspects a bug. According to Héctor Ramos (Parse), long time ago: "You should use a Date object, not a string, when dealing with dates in JavaScript.". Obviously this doesn't work!
Is my code wrong in some way?
Workaround:
queryResult._where.resultCeasesToBeValid = {'$lt' :{ "__type": "Date", "iso": today}}};
_where is a "private property" though and i wouldn't rely on it too much. Parse should fix this.
If you can [change the column type], i would suggest storing the date as a unix timestamp to avoid this kind of issues:
var timestamp = +new Date();
result.save({'resultCeasesToBeValid': timestamp});

Categories

Resources