Bin Floo
Bin Floo

Reputation: 9

dc bot check if message is older than X days js

So the question is: How do I get the days, the message is away from the current date (new Date().getDate())? Like if the message was sent 15 days before, age will be "15".

message is a message from discord. I get the date from the message when it was created with message.createdAt. This returns a timestamp, for e.g 2021-06-18T19:07:50.057Z

So my question is, how can I get the days, the message is away from Date.Now Like "The message was sent 13 days ago"

Upvotes: 0

Views: 290

Answers (2)

Joey
Joey

Reputation: 492

I use Moment.js for all my date calculations and it hasn't failed be yet.

CDN: https://cdn.jsdelivr.net/npm/[email protected]/moment.min.js

<script src="https://cdn.jsdelivr.net/npm/[email protected]/moment.min.js"></script>

let messageDate = '2021-06-18T19:07:50.057Z'

console.log(moment(new Date(messageDate)).fromNow('dd'))
// 18 days

If you'd like to just return the number then:

let messageDateNumber = Number(moment(new Date(messageDate)).fromNow('dd').replace(/[a-z]| /g,''))
    
    console.log('Message was sent ',messageDateNumber,' days ago')
    // Message was sent 18 days ago

Upvotes: 0

LeeLenalee
LeeLenalee

Reputation: 31401

You can convert it to a date and subtract the current date from it and the calculate that to an amount of days like so:

const oldDate = new Date('2021-06-18T19:07:50.057Z');
const today = new Date();

const diff = Math.abs(today-oldDate);
const daysBetween = Math.ceil(diff/(1000*3600*24)); //Round up

console.log(daysBetween)

Upvotes: 2

Related Questions