My current ReactJS application enables users to be able to submit time, date and text values, which is posted to a NodeJS backend.
Here is my current NodeJS code:
JavaScript
x
24
24
1
app.post("/send", function (req, res) {
2
let mailOptions = {
3
from: `${req.body.vals.email}`,
4
to: process.env.EMAIL,
5
subject: 'SUBJECT INFO',
6
html: `${req.body.vals.date} ${req.body.vals.time} ${req.body.vals.info}`,
7
};
8
9
10
transporter.sendMail(mailOptions, function (err, data) {
11
if (err) {
12
res.json({
13
status: "fail",
14
});
15
} else {
16
console.log("email sent");
17
res.json({
18
status: "success",
19
});
20
}
21
});
22
});
23
24
I want to be be able to schedule the emails to be sent at the given values of time and date from the front-end ReactJS.
I have tried to use node-schedule
but the whole date/time threw me off.
Edit:
This is the current date and time format that comes back.
date: 2022-08-28
time: 14:07
[edit: current solution not working]
JavaScript
1
29
29
1
app.post("/send", function (req, res) {
2
let mailOptions = {
3
from: `${req.body.vals.email}`,
4
to: process.env.EMAIL,
5
subject: 'SUBJECT INFO',
6
html: `${req.body.vals.date} ${req.body.vals.time} ${req.body.vals.info}`,
7
};
8
9
const dateParsed = new Date(`${req.body.vals.date}T${req.body.vals.time}Z`)
10
11
schedule.scheduleJob(dateParsed, function(){
12
transporter.sendMail(mailOptions, function (err, data) {
13
if (err) {
14
res.json({
15
status: "fail",
16
});
17
} else {
18
console.log("email sent");
19
res.json({
20
status: "success",
21
});
22
23
}
24
});
25
})
26
27
28
});
29
Advertisement
Answer
I don’t understand the problem with node-schedule
The API allows you to use date object instead of cron
JavaScript
1
7
1
const schedule = require('node-schedule');
2
const date = new Date(2012, 11, 21, 5, 30, 0);
3
4
const job = schedule.scheduleJob(date, function(){
5
console.log('The world is going to end today.');
6
});
7
Dates
Easiest way I can think of:
JavaScript
1
4
1
const date = '2022-08-28'
2
const time = '14:07'
3
4
console.log(new Date(`${date}T${time}Z`))
But I’m not sure if it’s best
Also, it will always give UTC time instead of local
Usually, dates are sent from the frontend as ISO already.