简体   繁体   中英

Node JS: MySQL is saving incorrect DateTime value in database

I am trying to save a record into a MySQL database using Node.js. Below is the code

const mysql = require('mysql2');
const errorCodes = require('source/error-codes');
const PropertiesReader = require('properties-reader');

const prop = PropertiesReader('properties.properties');

const con = mysql.createConnection({
    host: prop.get('server.host'),
    user: prop.get("server.username"),
    password: prop.get("server.password"),
    port: prop.get("server.port"),
    database: prop.get("server.dbname")
});

exports.createJobApplication = (event, context, callback) => {

        context.callbackWaitsForEmptyEventLoop = false;

        const sql = "INSERT INTO job_applications (idjob, iduser, cover_letter, applied_date) VALUES(?,?,?,?)";
        con.query(sql, [jobApplication.idjob, jobApplication.iduser, jobApplication.cover_letter, 1636366620000], function(err, jobApplicationResult) {
                    if (err) {
                        console.log(err.toString());

                        con.rollback(function() {
                            var response = errorCodes.save_failed;
                            callback(null, response);
                        });

                    } else {}

                }

Unfortunatly, I am failing to save the date as required. The above date 1636366620000 really represents 2021-11-08 10:17:00 but in MySQL database what I see is 0000-00-00 00:00:00 .

The applied_date field in MySQL is a DateTime field as well.

In addition to the hardcoded values I tried below JSON, but I get the same result

{
   "job_application":{
      "idjob":5,
      "iduser":112,
      "cover_letter":"ABCD EFGH IJK LMNOP QRST UV WXYZ",
      "applied_date":1636366620000
   },
   "milestones":[
      {
         "title":"title",
         "start_date":1636366620000,
         "end_date":1636366620000,
         "cost":250.0,
         "is_deleted":false
      },
      {
         "title":"title two",
         "start_date":1615544220000000,
         "end_date":1615544220000000,
         "cost":250.0,
         "is_deleted":false
      }
   ]
}

How can I fix this issue?

I found the issue. I have forgotted to wrap my DateTime integer with new Date() . So technically, this is how it should be

const sql = "INSERT INTO job_applications (idjob, iduser, cover_letter, applied_date) VALUES(?,?,?,?)";
        con.query(sql, [jobApplication.idjob, jobApplication.iduser, jobApplication.cover_letter, new Date(1636366620000)], function(err, jobApplicationResult)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM