I want to get all data between two dates from sql server with using mssql and query of sequelize in nodejs.
Start and End dates come from react frontend with axios.post.
For example start date is 2021-01-04T08:53:00.000Z and end date is 2021-01-05T21:00:00.000Z in express.
app.post('/getData', function (req, res) {
let startTime=req.body.start
let endTime=req.body.end
sequelize.query(` select Date_Time from S001T01 where Date_Time between ${startTime} and ${endTime}`, {
type: sequelize.QueryTypes.SELECT
}).then(result => {
console.log(result)
})
});
It returns many error, one of them is UnhandledPromiseRejectionWarning: SequelizeDatabaseError: Invalid column name '2021-01-05T21:00:00.000Z 23:59:00'..
In table viewer Date_Time column shown like that
I don't know what should I do.
Thanks for help.
You might have a wrong datetime format. 2021-01-05T21:00:00.000Z 23:59:00 doen't correspond to the traditional ISO 8601.
If you want all entries between 2021-01-04T08:53:00.000Z and 2021-01-05T21:00:00.000Z, your SQL query should look like this :
select Date_Time from S001T01 where Date_Time between 2021-01-04T08:53:00.000Z and 2021-01-05T21:00:00.000Z
You should also consider using modified datetime instead on concatenation.
Maybe something like thing should do the job :
var dt = new Date();
dt.setHours( dt.getHours() + 2 );
I hope it helped you.
Related
I have a problem and I want someone to help me.
My English is not that good, I'm sorry about that I'll try my best to explain the problem to you hopefully u can help me and thank you.
I'm working on an activity management platform where an employee login to his account and chose a project, then a table contains the days of a certain month under each day there is an input where he enters 1 or 0 if he worked that day or not this is how the UI looks:
When he clicks the button VALIDER (Validate in French) the data entered should be saved in mysql database.
to collect the data I used FormBuilder in angling, I defined as a form group that contains a form control that should get the name of the project, a form control that gets the month, and one for the year, and a form array that should get the values of the 3 inputs, when I console.log the value of the form I get this:
when I try to save the data in my database, I get the message successful, but when I look at my database nothing gets stored,
my database contain a table with :
projectName: varchar(45),
month: number,
year: number,
days: JSON
I think that the problem is that days are an array and not of type Jason because I tried saving an array, but I did like this: insert into project (projectName, days) values ('nomProjet', '['0', '0', '0']') and it gets saved but my days Array doesn't.
my node js code for the backend :
app.post('/cra/add', function (req, res) {
let nomProjet = req.body.projet;
let year = req.body.year;
let month = req.body.month;
let days = req.body.days;
if (nomProjet && year && month && days) {
connection.query('INSERT INTO projetcra2 ( nomProjet, month, year, days ) SET ( ? , ? , ? , ?) ',
[nomProjet, month, year, days],
function (error, results, fields) {
res.send({ status: 'success' , days});
res.end();
});
} else {
res.send({ status: 'failed', message: 'some data are required', loggedin: false });
res.end();
}
});
my formbuilder :
my save function to save to the database :
addDaysWorked() {
this.api.cra(this.form.value).subscribe(
(data: any) => {
console.log(data);
}, (error: HttpErrorResponse) => {
console.log(error);
}
)
}
when i test with postman :
my database :
I hope my problem is explained, if u think I can help with anything else let me know and thank you.
I'm not an expert at backend stuff by any means. However, I believe storing items as an array is inside of a single column in a database is not ideal. You should consider creating a new, separate table, for just days worked.
In the table, you could have a column that specified the date, whether or not he/she worked, and link obviously link this using a foreign key (like userId) to the users table or the main table in this case.
This would allow you to more easily insert the data. Since each day would just be a simple row, querying would also be simpler as you would just query data given a Timeframe (example: from beginning of August - End of August), a user (unique user ID).
Here are a couple other generic stack questions that might clarify as well.
Hope this helps!
Check out this resource as well
I have a use case where I have to retrieve a users record from the database via his date of birth.
The thing is that we have stored the date of birth of the user as datetime object which makes it very difficult to retrieve the users data, as we can not provide the exact date with timestamp.
I tried looking for a functions support in typeorm using which I can just compare the provided date with only the date part of the birth date in database but did not find any reference anywhere.
Don't convert your column to a string. Here's how to do it with a date/datetime/timestamp.
import { startOfDay, endOfDay } from 'date-fns';
import { Between, Equal } from "typeorm";
//...
let findArgs = {
where:{
date: Between(startOfDay(webInputArgs.date).toISOString(), endOfDay(webInputArgs.date).toISOString()),
userId: Equal(ctx.req.session.userId)
}
};
return entity.find(findArgs) as any;
You can use the query builder and the postgresql DATE_TRUNC() function:
const usersBornToday = await getManager()
.createQueryBuilder(User, "user")
.where(`DATE_TRUNC('day', "birthdatetime") = :date`, {date: '2021-03-27'})
.getMany()
Found the solution, We can actually use the LIKE operator, the only prerequisite is that we would have to convert the date to string,
something like
date_of_birth::text LIKE '2011-01-%'
If the DB type is MySQL, the CONVERT function will achieve the same approach used by #Vijender, which is to convert timestamp to text as below:
let date = '2022-01-25'; //yyyy-mm-dd, for Regex validation - /\d{4}\-\d{2}\-\d{2}/
date = `${date}%`;
queryResult.where('CONVERT(date_of_birth, char) LIKE :date', { date });
Todo:only show today stock list
const start = moment().startOf('day').toDate();
const end = moment().endOf('day').toDate();
const query=getManger()
.createQueryBuilder(stocks, 'stocks')
.andWhere('stocks.createdAt BETWEEN :start AND :end', { start, end })
I have a backend written on top of node.js, I'm using TypeORM as the ORM and Azure SQL Database to store my data. When I call the ORM's create() and save() functions, I'm passing in the correct date and time as can be seen below. But when I query the inserted data in the server, the timezone has shifted from -03:00 to +00:00. It maybe a normal behavior, since I'm new working with dates though.
This is the code where I call the create() in:
class CreateAppointmentsService {
public async execute({ provider, date }: RequestDTO): Promise<Appointment> {
const appointmentsRepository = getCustomRepository(AppointmentsRepository);
const roundDate = startOfHour(date);
const foundAppointment = await appointmentsRepository.findByDate(roundDate);
if (foundAppointment) {
throw Error('This date and time already has a booking.');
}
const appointment = appointmentsRepository.create({
provider,
date: roundDate,
});
await appointmentsRepository.save(appointment);
return appointment;
}
}
This is my debug information, showing date and time in expected timezone.
This is the data in the database. The field type is datetimeoffset and the server time is set to UTC (+00:00).
Thanks in advance! =)
[EDIT]: Explaining better: the time I posted to the database is rounded to 20:00 -03:00 (America/Sao_Paulo/Brasilia). If you look the column "created_at", the time is updated to UTC, but the column "data" only got the timezone set to +00:00, the time remais 20:00.
Found the problem! I forgot to set the "date" column to datetimeoffset in the typeORM model =(.
How it was:
#Column()
date: Date;
Changed to:
#Column('datetimeoffset')
date: Date;
Now it work wonders! The correct timezone is being set alongside the time. Cheers!
I am new to loopback. I have a date column start_date with DATE datatype.
when i try to fetch data with greater than or less than operations on start_date is working, but when i tried to fetch data equal to a date its not working:
the following is my fetching part:
Its working:
app.models.goals.find({where: {
start_date: {gt:'2016-03-31'}
}}, function(err, res) {
});
Its not working:
app.models.goals.find({where: {
start_date: '2016-03-31'
}}, function(err, res) {
});
Data is there in DB for 2016-03-31, but empty response. Is any syntax error.please help me to solve this.
I don't think there is anything wrong with the syntax. I tried the same syntax in both Strongloop API Explorer and with loopback Node.JS API and found it to be working.
However, While checking these out, I noticed that when the date string doesn't have time and TZ information in it, the time portion is assumed to be 00.00.00 in the local timezone. For example, when I used the following code on my "Sandbox" model:
Sandbox.find({where: {myDateProp:'2016-04-2'}}, function(err, res){
console.log('results are %j', res);
next();
});
The retrieved results record contained:
Retreived results are [{"myStringProp":"String5","myDateProp":"2016-04-01T18:30:00.000Z","id":"56fc1dc6b9de1a6b06750b98"}]
Notice that my search for 2016-04-2 actually matched a record with date 2016-04-01 6:30 PM which is the GMT equivalent of 2016-04-2 00:00:00 IST.
I am guessing that this may have something to do with the behaviour that you observe. I'd recommend you to check the Date value of start_date of the record in the database. Then, if necessary add the time and timezone information to the filter in your code.
I'm trying to store comments for a blog in Cassandra and have come up with this schema (got the idea from here):
create table comments ( slug varchar, ts timestamp, value text, primary key (slug,ts));
Using CQL (I'm using node.js with Helenus driver) I'm trying to add some data to it, here's what I've got so far:
var helenus = require('helenus'),
pool = new helenus.ConnectionPool({
hosts: ['localhost:9160'],
keyspace: 'blogks'
});
pool.on('error', function(err) {
console.error(err.name, err.message);
});
module.exports.addComment = function(slug, comment,callback){
pool.connect(function(connErr,keyspace){
if(connErr){
callback(connErr);
return;
}
var cql = "INSERT INTO comments (slug,ts,value) VALUES (?, ?, ?);";
pool.cql(cql,[slug,serializeDate(new Date()),serializeJSON(comment)],function(err,results){
callback(err,results);
});
});
}
function serializeDate(date){
var dateSerializer = new helenus.Marshal('DateType');
return dateSerializer.serialize(date).toString('hex');
}
function serializeJSON(data){
var utf8Serializer = new helenus.Marshal('UTF8Type');
return utf8Serializer.serialize(JSON.stringify(data)).toString("hex");
}
The idea being you can pass in a comment json object to this method, and push it to cassandra. I'm calling it like this to test:
var comments = require('./comments.js');
comments.addComment("myslug",{id:2,name:"Alex",comment:"Hello!"},function(e,r){
console.log(e);
console.log(r);
})
but whenever I do (I tried various CQL drivers), I get this cryptic error message:
[HelenusInvalidRequestException: unable to coerce 'value' to a formatted date (long)] name: 'HelenusInvalidRequestException'
I tried changing the timestamp to be all different data types, but no luck. The very strange thing is that at first, my primary key was just the slug itself, and then it did work. However, I want to store all comments in one row ordered by timestamp, therefore I had to go with this approach of using two columns for the primary key. Any ideas?
EDIT So based on rs_atl's suggestion, here's what I've tried:
This line:
dateSerializer.serialize(date).toString('hex')
did in fact return garbage (0000013ccfacf5c4), I must have misunderstood how to use the API. So here's what I tried instead:
I tried just new Date().getTime() which in JS does in fact return Unix-style epoch, but that didn't work I got the same error. I then tried using moment.js to try and format the string:
moment().format("YYYY-MM-DD HH:mm:ss")
which seems to be returning the correct format, but again. Same error. Then I tried this:
moment().format("YYYY-MM-DD HH:mm") + "Z"
no luck. I then tried this:
moment().format("YYYY-MM-DD HH:mmZ")
which does in fact add the timezone info at the end, but still, no luck. Any ideas?
it seems you are using the wrong CQL version. You expect to use CQL 3.0.0 but the driver defaults to CQL2. You need to specify the correct CQL version in the initialization.
pool = new helenus.ConnectionPool({
hosts: ['localhost:9160'],
keyspace: 'blogks',
cqlVersion: '3.0.0'
});
And also please ensure you are using the latest version (0.6.2 as of now) of Helenus.
I'm not exactly sure what the output of this line is:
return dateSerializer.serialize(date).toString('hex');
but this is where your issue is. It appears that you are not outputting a valid date that Cassandra understands. A valid date is either:
A Unix-style epoch as a long value.
A string in one of the following forms:
yyyy-mm-dd HH:mm
yyyy-mm-dd HH:mm:ss
yyyy-mm-dd HH:mmZ
yyyy-mm-dd HH:mm:ssZ
yyyy-mm-dd'T'HH:mm
yyyy-mm-dd'T'HH:mmZ
yyyy-mm-dd'T'HH:mm:ss
yyyy-mm-dd'T'HH:mm:ssZ
yyyy-mm-dd
yyyy-mm-ddZ
Check to make sure you are writing one of these valid timestamp types.
For timestamps, I've always use int in milliseconds to represent time.
Try:
Date.now()
instead of:
serializeDate(new Date())