How does Discord do their formatting for their dates, today & yesterday?

Viewed 749

I'm currently working on something that is discord based for a website and I would love to be able integrate their date-format.

What am I talking about?

I'm talking about this:

UserOne Yesterday at 17:03

UserTwo Today at 13:06

Example:

enter image description here

2 Answers

You can find a quick and dirty solution below, although I would probably use date-fns for this. The logic would be with the same with that too. Check if the day is today or yesterday. If it is, print the word and the time. If it's not, print the date only:

function isSameDay(date1, date2) {
  return (date1.getDate() === date2.getDate() &&
    date1.getMonth() === date2.getMonth() &&
    date1.getFullYear() === date2.getFullYear())
}

function formatDate(d) {
  const today = new Date()
  const yesterday = new Date(today)
  yesterday.setDate(yesterday.getDate() - 1)
  const timeOptions = {
    hour: '2-digit',
    minute: '2-digit'
  }

  if (isSameDay(d, today)) {
    // it's today
    return `Today at ${d.toLocaleTimeString(undefined, timeOptions)}`
  }

  if (isSameDay(d, yesterday)) {
    // it was yesterday
    return `Yesterday at ${d.toLocaleTimeString(undefined, timeOptions)}`
  }

  return d.toLocaleDateString()
}

// examples
console.log({
  'Now': formatDate(new Date()),
  // geez, this yesterday date is ugly :D
  'Yesterday': formatDate(new Date(new Date().setDate(new Date().getDate() - 1))),
  'On the 5th of January': formatDate(new Date('2021-01-05 11:54'))
})

With date-fns:

const format = require('date-fns/format');
const isToday = require('date-fns/isToday');
const isYesterday = require('date-fns/isYesterday');

function formatDate(d) {
  if (isToday(d)) {
    return `Today at ${format(d, 'kk:mm')}`;
  }

  if (isYesterday(d)) {
    return `Yesterday at ${format(d, 'kk:mm')}`;
  }

  return format(d, 'dd/MM/yyyy');
}

Use formatRelative from date-fns.

import {formatRelative} from 'date-fns';

const date = new Date('2021-08-24');
const now = new Date(); // 2021-08-25 as of today

const formattedDate = formatRelative(date, now); // => yesterday at 1:00 PM
Related