【问题标题】:How to convert args[1] to date for input into MySQL DB (Javascript, DiscordJS)?如何将 args[1] 转换为日期以输入 MySQL DB(Javascript,DiscordJS)?
【发布时间】:2023-03-08 08:04:01
【问题描述】:

我创建了一个带有命令处理程序的不和谐机器人。我正在尝试制作一个命令,该命令采用用户消息的 args[1] 并将其输入到 MySQL 字段中。

在这种情况下,它将是>birthdayadd @user MM/DD/YYYY。当前代码采用 args[1] 如果它等于长度 10 并将其添加到 MySQL。

当前的问题意味着它在 mySQL 中的格式不正确,我无法创建一个命令来排序并返回特定时间跨度内的生日。

我将如何转换它,以便将 args[1] 转换为日期字符串(只取日和月),然后输入到格式化为 DATE 的 mySQL 列?

代码如下:

const Discord = require("discord.js");

module.exports.run = async (bot, message, args, con) => {

    let mention = message.mentions.users.first() || bot.users.get(args[0]);
    if (!mention) return message.reply("You must mention someone or give their ID!");

    con.query(`SELECT bday FROM alltime WHERE user = '${mention.id}' AND guild = '${message.guild.id}'`, function (error, results, fields) {
        if (error) throw error;

        if (!args[1]) return message.reply("You must specify a birthdate to add in the format DD/MM");
        if (args[1].length < 10) return message.reply("format must be DD-MM-YYYY");
        if (args[1].length > 10) return message.reply("format must be DD-MM-YYYY");

        if (args[1].length === 10) {
            con.query(`UPDATE alltime SET bday = '${args[1]}' WHERE user = '${mention.id}' AND guild = '${message.guild.id}'`);
            message.channel.send(`Birthday set to ${args[1]} for ${bot.users.get(mention.id).username}`);
        };

    })
}
module.exports.help = {
    name: "birthdayadd",
    usage: "``prefix`` @member DD/MM",
    description: "Add a users birthday into the database",
}
bot = discord client

con = MySQL connection details

对此的任何帮助将不胜感激。

【问题讨论】:

    标签: javascript mysql date formatting discord


    【解决方案1】:

    我建议您使用moment.js 进行格式化,MySQL 使用 YYYY-MM-DD

    MySQL 以 'YYYY-MM-DD' 格式检索和显示 DATE 值。 (https://dev.mysql.com/doc/en/datetime.html)

    你可以用时刻来

    1. 接受用户的日期字符串 - 这接受多种不同类型的日期
    2. 将其格式化为 YYYY-MM-DD

      var date = moment("2004 年 3 月 17 日"); console.log(date.format("YYYY-MM-DD")); //2004-03-17

    如需仅获取月份和日期,请参考Compare only day and month with date field in mysql

    【讨论】:

    • var date = moment(${args[1]}); console.log(date.format("YYYY-MM-DD"));时刻没有定义?
    • Nvm,安装了库。谢谢!!
    猜你喜欢
    • 2010-12-18
    • 2011-08-02
    • 1970-01-01
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多