0

I want to format the date in JavaScript. Currently I am storing the date using the Date function +new Date(). And I am formatting the date using moment.js. I am using the calendar () function of moment.js and fromNow() function. The calendar function is formatting the date like Today at 11:00Pm and fromNow() is formatting like 5hours ago. But I want if the message time is less than hour it should show 40 minutes ago otherwise it should show Today at 11:00Pm

Required output

//if message time less than 1 hour
10 minutes ago
49 minutes ago
//If it's more than one hour
Today at 4:00am
Yesterday at 11:00pm

enter image description here

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Wani
  • 61
  • 2
  • 9
  • 1
    Actually you answered your own question. Just write a function where you check for the given time and return the matching case like (pseudocode) `if (passedTimeInMinutes < 60) { return valueAsMinutes } else { return valueAsTimestamp }` – PRSHL Sep 06 '21 at 17:28
  • This question is similar to: https://stackoverflow.com/questions/3177836/how-to-format-time-since-xxx-e-g-4-minutes-ago-similar-to-stack-exchange-site – kup Sep 06 '21 at 17:42
  • Note that moment is considered legacy, there are more modern alternatives as you can see in [their page](https://momentjs.com/docs/#/-project-status/) – NuLo Sep 06 '21 at 18:28

2 Answers2

0

remember if you want to develop or want to develop something. There is a huge probability that one Chinese Already did it.

install the timeago.js

npm install timeago.js

Just look for it at Google. PD: I do not meant to offend anybody, it was a reality

Ernesto
  • 3,944
  • 1
  • 14
  • 29
-1

EDIT:

Here is a version that does not rely on 3rd party plugins, as some people noted in the comments, Moment.js is now longer maintained, an modern date functions are able to handle this job pretty well on their own, although, of course, there might be some edge cases to be considered.

const date = new Date(Date.now() - 600000);
document.getElementById("date").value = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`;

document.getElementById("calc").addEventListener("click", () => {
  document.getElementById("output").textContent = getTimeMessage(document.getElementById("date").value);
});

getTimeMessage = (timeStamp) => {
  const aMonths = ["January", "Februray", "March", "April", "Mai", "June", "Juli", "August", "September", "October", "November", "December"];
  const now = new Date();
  const messageTime = new Date(timeStamp);
  const diff = (now - messageTime);
  const aDiff = {
    sec: parseInt(diff / 1000),
    min: parseInt(diff / 1000 / 60),
    h: parseInt(diff / 1000 / 60 / 60),
    d: parseInt(diff / 1000 / 60 / 60 / 24)
  };
  const formatDayOfMonth = (day) => {
    // borrowed from https://stackoverflow.com/a/18289487/13987708
    const array = `${day}`.split("").reverse(); // E.g. 123 = array("3","2","1")
    array[0] = +array[1] === 1 ? 0 : +array[0]; // Number is in the teens
    
    switch (array[0]) {
      case 1: return `${day}st`;
      case 2: return `${day}nd`;
      case 3: return `${day}rd`;
      default: return `${day}th`;
    }
  };
  const padNumber = (number) => {
    return (number < 10) ? `0${number}` : number;
  };
  const formatHoursOfDay = (hour, militaryTime) => {
    return padNumber(!militaryTime ? hour > 12 ? hour - 12 : hour : hour);
  };
  const formatedMonth = aMonths[messageTime.getMonth()];
  const formatedDay = formatDayOfMonth(messageTime.getDate());
  const formatedHours = formatHoursOfDay(messageTime.getHours(), true);
  const formatedMinutes = padNumber(messageTime.getMinutes());
  const timeString = `${formatedHours}:${formatedMinutes}`;
  const dateString = `${formatedMonth} the ${formatedDay}`;

  if (aDiff.min < 60) {
    return `Message received ${aDiff.min} minutes ago`;
  } else if (now.getDate() === messageTime.getDate() && aDiff.d <= 1) {
    return `Message received today at ${timeString}`;
  } else if ((now.getDate() - 1) === messageTime.getDate() && aDiff.d <= 2) {
    return `Message received yesterday at ${timeString}`;
  } else if (now.getFullYear() === messageTime.getFullYear()) {
    return `Message received on ${dateString} at ${timeString}`;
  } else {
    return `Message received on ${dateString}, ${messageTime.getFullYear()} at ${timeString}`;
  }
}
<label>
Massage Date:
<input type="text" id="date">
</label>
<button id="calc">Show Result</button>

<p id="output"></p>

Original Post:

So basically all you need is to check the difference between the current date and the date of your massage.

Moment.js has a function to do that.

After you got the difference, you just need some if else blocks to spit out the correct phrase for your use case.

Wrap everything in a contained function and you can use it in any project you need it in.

document.getElementById("date").value = moment().subtract(10, "minutes").format("YYYY-MM-DD HH:mm");

document.getElementById("calc").addEventListener("click", () => {
  document.getElementById("output").textContent = getTimeMessage(document.getElementById("date").value);
});

getTimeMessage = (timeStamp) => {
  const now = moment();
  const messageTime = moment(timeStamp);
  const diff = now.diff(messageTime, 'minutes');

  if (diff < 60) {
    return `Message received ${diff} minutes ago`;
  } else {
    if (now.diff(messageTime, 'days') < 1) {
     return `Message received today at ${messageTime.format("HH:mm")}`;
    } else {
      if (now.diff(messageTime, 'years') < 1) {
        return `Message received on ${messageTime.format("MMMM Do")} at ${messageTime.format("HH:mm")}`;
      } else {
        return `Message received on ${messageTime.format("MMMM Do YYYY")} at ${messageTime.format("HH:mm")}`;
      }
    }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<label>
Massage Date:
<input type="text" id="date">
</label>
<button id="calc">Show Result</button>

<p id="output"></p>
Christian
  • 427
  • 3
  • 7