I wanna Request from nodejs Sequelize to mysql to data of a date that comes from query and there may not be any date
Actually I have no idea how to search by date but i thought it can be with params
can any one help me
Here is what I tried:
.findAndCountAll({
where: {
[Op.or]: [
{ createdAt: { [Op.eq]: moment("2023-01-15").toDate() } },
]
})
and when i send date from react as a string and in nodejs i change it to date time it will show the day before date
ex:
console.log(moment(2023-01-15).toDate())
// 2023-01-14T21:00:00.000Z
You can build your filter if date is present and use $between to filter the previous day:
const date = "2023-01-15";// Some date you received from the client or empty
let where = {};
if (date) {
// Filter day before date
const endDate = moment(date).toDate();
const startDate = endDate;
startDate.setDate(startDate.getDate() - 1);
where = {
from: { $between: [startDate, endDate] },
}
}
// Execute the query
.findAndCountAll(where);
while implementing search by date from postgres db using sequelize postgres and nodejs I got this warning.
Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged.
router.get("/:key", async (req, res) => {
try {
const searchActivity = await initActivityModel();
let data = await searchActivity.findAll({
where: {
...
createdAt: { [Op.like]: "%" + req.params.key + "%" },
// createdAt: { [Op.between]: ["2023-01-06", "2023-01-07"] }, // this is working
},
});
I'm trying to create a moment object with a date string that is not in a recognized format. how to fix this?
Hi there I'm new and prisma and trying to select future dates in prisma and not grab any 'expired' days.
I'm seeing in the docs that there is a prisma.now() but cant see it in the console when I log out cosole.log(prisma)
Does anybody know a good solution to this?
My created_at is grabbing this format: 2022-01-13 12:00
app.get("/ques", async function (req, res) {
console.log("PRISMA", prisma.NOW());
const allQues = await prisma.que.findMany({
where: {
created_at: {
gte: prisma.NOW(),
},
},
});
res.status(200).send(allQues);
});
I'm not sure that such thing even exists? (prisma.NOW())
now() is just a function that you can use in your schema file to set default value, for example:
model User {
registeredAt DateTime #default(now())
}
In your app code you can just use regular Javascript Date object, for example:
const allQues = await prisma.que.findMany({
where: {
created_at: {
// new Date() creates date with current time and day and etc.
gte: new Date()
},
},
});
This is my code right now:
const Grace = sequelize.define('grace', {
userId: Sequelize.TEXT,
tribeName: Sequelize.TEXT,
server: Sequelize.TEXT,
hours: Sequelize.INTEGER,
date: Sequelize.DATE,
datef: Sequelize.DATE,
});
As you can see datef is stores as a date. datef is a future date. Example: current time + 36h
else if (command === 'showdb'){
var now = Date.now();
const gracep = await Grace.findAll({
where: {
datef: {
$gt: now,
},
},
});
}
What I want to do is to have it fetch the results in the db, where datef is greather than current timestamp.
The thing is datef is stored as: 2018-06-07 05:11:04.221 +00:00
And the var now is: 1528330290003
So I'm pretty sure that's the reason why it's not working, as it's outputing [], when it shouldn't.
Not sure what to do.
I've used date comparisons in Sequelize for WHERE clause when I want to compare something against the current date.
In my case I converted the current timestamp (from Date.now()) to an ISO string like so:
const now = (new Date()).toISOString();
I didn't have any problems when calling using an [Op.gte] or [Op.lte] operator to compare against the stored dates.
date.now() returns the number of milliseconds since midnight 01 January 1970 UTC. It is the same as new Date().valueOf()
here is what you can do
where : { datef : { [Op.gt]: new Date() } },
Sequelize documentation
In model schema,
Using
updated: {
type: Date,
default: Date.now
In server.js
put(function(req, res) {
var query = {name: req.params.name};
// use our bear model to find the bear we want
Domain.find(query, function(err, domains) {
if (err)
res.send(err);
var domain = domains[0];
domain.password = req.body.password; // update the bears info
domain.updated = new Date();
// save the bear
domain.save(function(err, data) {
if (err)
res.send(err);
res.json({ status: 'success', message: 'domain updated!' }, data);
});
});
});
However,
In db side it shows,
"updated": "2016-02-27T16:20:42.941Z"
But, my timezone is UTC+02.00
So it should be like 18:20:42
What I'm doing wrong?
I'm using moment-timezone
npm install moment-timezone
const moment = require('moment-timezone');
const dateThailand = moment.tz(Date.now(), "Asia/Bangkok");
console.log(dateThailand); // "2018-08-20T16:35:14.033+07:00"
*** Asia/Bangkok +07:00
Schema in the mongoose.
const categorySchema = new Schema(
{
_id: {type: mongoose.Schema.Types.ObjectId, auto: true},
c_name: String,
created_by: String,
created_date: {type: Date, default: dateThailand},
updated_by: String,
updated_date: {type: Date, default: dateThailand}
}, {_id: false}
);
See up that created_date, updated_date: {type: Date, default: dateThailand }
Read more: http://momentjs.com/timezone/docs/
*If you using Robo 3T tool.
You can set "Display Dates In..."
Options > Display Dates In... > Local Timezone
:) Work for me.
The timestamps are timezone agnostic, stored as a unix timestamp. This timestamp will work across timezones, and node interprets it using current timezone of the server. The date you've shown is correctly stored. As soon as you'll retrieve it, if your server's timezone is UTC+2, it will show you correct time.
There is nothing wrong in your code. MongoDb saves date in UTC format no matter in whichever timezone you try to insert your date.
If you log domain.updated before saving in DB, result will be UTC+2 (your local time)
If you see updated column in DB, result will be in UTC
If you fetch updated column value from DB, then again result will be in UTC+2 (your local time)
I changed this,
var utc = new Date();
utc.setHours( utc.getHours() + 2);
domain.updated = utc;
Now it works.
You can create a Date Object from a specific UTC time:
new Date(Date.UTC(year, month, day, hour, minute, second))
Remember that no matter what you use to set time in mongoose schema, mongoose will always use UTC time, hence you need to dynamically allocate the UTC timestamp inside the Schema. Here it goes :-
var current = new Date();
const timeStamp = new Date(Date.UTC(current.getFullYear(),
current.getMonth(),current.getDate(),current.getHours(),
current.getMinutes(),current.getSeconds(), current.getMilliseconds()));
//Here goes your schema
const auditSchema = mongoose.Schema({
dateTime : { type: Date, default : timeStamp }
})
Using moment.js it is as easy as:
var moment = require('moment');
var utcDate = moment.utc().toDate();
Enjoy!