How to convert MYSQL Timestamp to CST time with Javascript? - javascript

If someone could help me with this I´d appreciate it!
I need to convert MYSQL Timestamp 2022-09-14T05:08:32.000Z to my local time (Central Standard Time) and then be able to pass that result to EJS. I am passing the data to my EJS view with this route, but not sure how to convert this timestamp before passing it to EJS.
This screenshot shows the 'rows' values which are being passed to EJS.
rutas.get('/historial', loggedIn, async (req, res, next) => {
await pool.query('SELECT * FROM historial WHERE id = ? AND calidaddeltrade = ? OR calidaddeltrade = ?', [req.user.id, 'Excelente', 'Buena'], function (err, rows, fields) {
if (err) { throw err };
res.render('./historial', { rows: rows});
console.log(rows);
})
});
Does anyone know how could I do this with Javascript? Thanks!!

Related

How to send multiple query results from backend to frontend in node

I am making a simple check-in and check-out system for employees. In the main panel I want to show the number of hours worked per day and in another field the weekly total.
I can now show the hours per day in a table, the problem comes when I have to show the total since I make that query to the database with another query.
With the following code I perform the query and perform a render in the index view using the EJS templates.:
router.get('/', (req, res) => {
const week = DateTime.now().weekNumber;
conexion.query('SELECT * FROM assistance WHERE week = ?', week, (error, results) => {
if(error){
throw error;
}else{
res.render('index', {results: results});
}
})
});
With this code I perform the query of the total hours. but I don't know how to show it in the same index view since it is a separate query from the first one:
conexion.query('SELECT time_format(SUM(TIMEDIFF(a.exit, a.entry)), "%H:%i") AS hours from assistance a WHERE a.week = ?', week, (error, results) => {
if(error){
throw error;
}else{
return('index', {totalHours: results});
}
})
In this way I am trying to receive the information in the index view with EJS:
<div>
<div>Total hours:<%= totalHours%></div>
</div>
Use try/catch async-await, then just do both queries.
router.get('/', async(req, res) => {
const week = DateTime.now().weekNumber
try {
// query 1
const totalHours = await conexion.query('SELECT time_format(SUM(TIMEDIFF(a.exit, a.entry)), "%H:%i") AS hours from assistance a WHERE a.week = ?', week)
// query 2
const results = await conexion.query('SELECT * FROM assistance WHERE week = ?', week)
res.render('index', {
totalHours,
results
})
} catch {
res.render('error-page')
}
})

How to implement promises in nodejs?

I made this project based on a YT tutorial but adding some extra features
image
the problem I have is the following, this is the code that is used to show the data of the database
controller.list = (req, res) => {
req.getConnection((err, conn) => {
conn.query("SELECT * FROM usuarios ", (err, usuarios) => {
if(err){
res.json(err)
}
res.render("usuarios", {
data: usuarios
})
})
})
}
but I don't know how to modify it so that in the part that says "usado" it shows me the number of times that the "Codigo" is repeated. I know that with a MySQL query similar to this one 'SELECT COUNT(*) AS namesCount FROM names WHERE age = ?' I can show the number of times it repeats, but I don't know how to implement this in the controller, I know I can do it with promises but I don't know how to modify the code to implement it.

How do I get all objects with a specific start date

I'm trying to use a date parameter that comes in through the request and return all objects that have that date. I do not want to look at the time stamp, just the year, month, day.
The following in the controller file of mongoose finds dates that match a specific day:
export const getBookingByDate = (req, res) => {
Booking.find({start: {$gt: req.params.bookingDate}}, (err, booking) => {
if(err){
res.send(err);
}
res.json(booking);
})
}

NodeJs insert current Datetime field into MySQL db

I'm trying to insert a DATETIME field into my MySQL db.
var dt = require('moment')().format('YYYY-MM-DD HH:mm:ss');
pool.query(
`insert into login(id, id_utente, data_login) values(NULL,?,?)`,
[results[0].id],
[dt],
(error, results, fields) => {
}
);
I get this error:
C:\Users\tiger\Desktop\prova\REST_API_WITH_MYSQL-master\node_modules\mysql\lib\protocol\Parser.js:437
throw err; // Rethrow non-MySQL errors
^TypeError: this._callback.apply is not a function
If I try this code, everything comes right:
pool.query(
`insert into login(id, id_utente, data_login) values(NULL,?,"2021-01-27 00:00:00")`,
[results[0].id],
//[dt],
(error, results, fields) => {
}
);
What i'm doing wrong?
You have your parameters in 2 separate arrays. Put your parameters in the same parameter array.
pool.query(
`insert into login(id, id_utente, data_login) values(NULL,?,?)`,
[results[0].id, dt],
(error, results, fields) => {
}
);
The correct format probably is YYYY-MM-DD HH:MM:SS(I think it depends on MySQL configuration, but this is the default) as the docs points out.
So you should try using moment's format() method like this:
const myDate = moment(data.myTime.format('YYYY/MM/DD HH:mm:ss')).format("YYYY-MM-DD HH:mm:ss");
pool.query(
`insert into login(id, id_utente, data_login) values(NULL,?,?)`,
[results[0].id, myDate],
(error, results, fields) => {
}
);

pass a json result of a mysql query as a param to my ejs in Node/express

I have a query to get all my users. I have been doing res.json(rows) to display to screen until now. Now I want to pass the object obtain from the query to a ejs file and display it. If I do like my code below, the object pass is a string and I can´t iterate or obtain the fields.
What is the best way to achive what I´m trying to do?
router.get("/users", (req, res) => {
const connection = getConnection();
const newLocal = "SELECT * FROM client";
connection.query(newLocal,(err, rows, fields) => {
if (err) {
console.log("Error "+err);
res.sendStatus(500);
return;
}
// res.json(rows);
res.render("users.ejs", {users: JSON.stringify(rows)});
});
});
It's because you're turning your Array rows into a String. Remove JSON.stringify

Categories

Resources