[英]How to automatically calculate INSERTET DATE - current date
i have a table:我有一张桌子:
CREATE TABLE IF NOT EXISTS bands (
id serial PRIMARY KEY,
name VARCHAR UNIQUE NOT NULL,
creationDate DATE not NULL,
years DATE not NULL
);
I only want to pass name
and creation date
.我只想传递
name
和creation date
。 what i want is that years
will return currentdate - creationDate
.我想要的是
years
将返回currentdate - creationDate
。 The problem is that I do not really know where i should correctly change my code, because im using Node project
.问题是我真的不知道我应该在哪里正确更改我的代码,因为我使用的是
Node project
。 My code looks like this:我的代码如下所示:
const express = require("express");
const app = express();
const pool = require("./db");
app.use(express.json());
// Routes
app.post("/bands", async (req, res) => {
try {
const { name, creationDate } = req.body;
const newBand = await pool.query(
"INSERT INTO bands (name, creationDate,years) VALUES ($1, $2) RETURNING *",
[name, creationDate]
);
res.json(newBand);
} catch (err) {
console.error(err.message);
}
});
app.get("/bands", async (req, res) => {
try {
const allBands = await pool.query("SELECT * FROM bands");
res.json(allBands);
console.log(allBands);
} catch (err) {
console.error(err.message);
}
});
app.get("/bands/:bandsName", async (req, res) => {
console.log(req.params);
const { bandsName } = req.params;
try {
const todo = await pool.query("SELECT * FROM bands WHERE name = $1", [
bandsName,
]);
res.json(todo.rows[0]);
} catch (err) {
console.error(err.message);
}
});
app.put("/bands/:id", async (req, res) => {
try {
const { id } = req.params;
const { name, creationDate } = req.body;
const updateTodo = await pool.query(
"UPDATE band SET name = $1, creationDate = $2 WHERE id = $3",
[name, creationDate, id]
);
res.json("Udało się, zaaktualizowane");
} catch (err) {
console.error(err.message);
}
});
app.delete("/bands/:id", async (req, res) => {
try {
const { id } = req.params;
const deleteTodo = await pool.query("DELETE FROM bands WHERE id = $1", [
id,
]);
res.json("Usunięto");
} catch (err) {
console.error(err.message);
}
});
app.listen(3000, () => {
console.log("server is listening on port 3000");
});
Can anyone tell me where should i change my code so "years"
will automatically calculate without me having to put the data in postman?谁能告诉我应该在哪里更改代码,以便
"years"
自动计算而无需将数据放入邮递员?
const { name, creationDate } = req.body;
const d = new Date(creationDate );
const year = d.getFullYear();
Create a date object and retrieve the year would do it创建一个日期对象并检索年份就可以了
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.