Show date like 30-04-2020 instead of 2020-04-30 from mysql database using javascript

落花浮王杯 提交于 2021-01-28 05:16:38

问题


I'am building a small webapplication for personal business purpose. I have come far from looking around and looking how to program a webapplication. So I can added reservations and edit them and also delete them. The last days I have been looking how to save a date into Mysql database and how to show it in the webapplication. For so far its working but its not showing in the right format. If you see the attachment Date sample I want the date like this "30-04-2020" and not like "2020-04-30". For some reason I just cant configure it. Can someone help me with that. I will put some code. The code below

database connection;

const db = mysql.createConnection ({
host: 'localhost',
user: 'root',
password: '',
database: '',
dateStrings: true,

});

My insert query

let query = "INSERT INTO `players` (achternaam, telefoonnummer, adres, email, typetaart, aantalpersonen, smaak, vulling, opmerking, prijs, reedsVoldaan, nogTeVoldoen, date, image, user_name) VALUES ('" +
                                achternaam + "', '" + telefoonnummer + "', '" + adres + "', '" + email + "', '" + typetaart + "', '" + aantalpersonen + "', '" + smaak + "','" + vulling + "', '" + opmerking + "', '" + prijs + "', '" + reedsVoldaan + "', '" + nogTeVoldoen + "',STR_TO_DATE ('" + date + "', '%d-%m-%Y'), '" + image_name + "', '" + username + "')";

homepage

    exports.homepageMTaartenAdmin = function(req, res, next){

   var user =  req.session.user,
   userId = req.session.userId;
   console.log('ddd='+userId);
   if(userId == null){
      res.redirect("login");
      return;
   }

   var sql="SELECT * FROM `players` ORDER BY id ASC"; // query database to get all the players


   db.query(sql, function(err, result){
      res.render('homepageMTaartenAdmin', {players:result});    

   });       
}

Date sample

If you need any further information please tell me. I appreciate your help.

Kind regards,

William Ashoti


回答1:


In MySQL, you can use date function date_format() to display your date in the desired string format:

SELECT 
    achternaam, 
    telefoonnummer, 
    adres, 
    email, 
    typetaart, 
    aantalpersonen, 
    smaak, 
    vulling, 
    opmerking, 
    prijs, 
    reedsVoldaan, 
    nogTeVoldoen, 
    DATE_FORMAT(date, '%d-%m-%Y') date,  --> here 
    image, 
    user_name
FROM `players` 
ORDER BY id ASC

If you want to avoid enumerating all the columns, you can add a new column in the result set with a different identifier, like:

SELECT p.*, DATE_FORMAT(date, '%d-%m-%Y') formatted_date
FROM `players` p
ORDER BY id ASC


来源:https://stackoverflow.com/questions/61031353/show-date-like-30-04-2020-instead-of-2020-04-30-from-mysql-database-using-javasc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!