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:
app.post("/send", function (req, res) { let mailOptions = { from: `${req.body.vals.email}`, to: process.env.EMAIL, subject: 'SUBJECT INFO', html: `${req.body.vals.date} ${req.body.vals.time} ${req.body.vals.info}`, }; transporter.sendMail(mailOptions, function (err, data) { if (err) { res.json({ status: "fail", }); } else { console.log("email sent"); res.json({ status: "success", }); } }); });
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]
app.post("/send", function (req, res) { let mailOptions = { from: `${req.body.vals.email}`, to: process.env.EMAIL, subject: 'SUBJECT INFO', html: `${req.body.vals.date} ${req.body.vals.time} ${req.body.vals.info}`, }; const dateParsed = new Date(`${req.body.vals.date}T${req.body.vals.time}Z`) schedule.scheduleJob(dateParsed, function(){ transporter.sendMail(mailOptions, function (err, data) { if (err) { res.json({ status: "fail", }); } else { console.log("email sent"); res.json({ status: "success", }); } }); }) });
Advertisement
Answer
I don’t understand the problem with node-schedule
The API allows you to use date object instead of cron
const schedule = require('node-schedule'); const date = new Date(2012, 11, 21, 5, 30, 0); const job = schedule.scheduleJob(date, function(){ console.log('The world is going to end today.'); });
Dates
Easiest way I can think of:
const date = '2022-08-28' const time = '14:07' 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.