Search code examples
discord.js

Discord.js Time command


Const currentDate = new Date();
client.on('message', msg => {
  if(msg.author.bot) return;
  if(msg.content === `${prefix}time`) {
    msg.channel.send(currentDate.toLocaleString());
  }
})

This does provide the right time for MY timezone but is there anyway to make the bot send a time stamp, different regions see a different time?


Solution

  • Well, you can use Discord's <t:unix-timestamp:t> feature. It'll vary depending on the timezone of the user seeing the message. You can get the Unix timestamp with Date.now() (const unixTimestamp = Date.now()) but that's the timestamp in milliseconds so you will need to divide it by 1000 for seconds.

    You also want to use Math.floor since dividing milliseconds will give a decimal value and Discord's timestamp thing won't work.

    const unixTimestamp = Math.floor(Date.now() / 1000)

    Here's the command using your command handler:

    client.on('message', (msg) => {
      if (msg.author.bot) return;
      if (msg.content === `${prefix}time`) {
        const unixTime = Math.floor(Date.now() / 1000);
        // you can remove the :t in the end so it's a full date
        // :t makes it only the time
        msg.channel.send(`The current time is <t:${unixTime}:t>`);
      }
    });
    

    Also, I recommend using messageCreate and not message as it's deprecated.