如何在 JavaScript 中格式化时间戳

How to format timestamp in JavaScript

我想在 JavaScript 中格式化日期。目前我正在使用日期函数 +new Date() 存储日期。我正在使用 moment.js 格式化日期。我正在使用 moment.js 和 fromNow() 函数的 calendar () 函数。日历函数将日期格式化为 Today at 11:00Pm fromNow() 将日期格式化为 5hours ago。但我想如果消息时间少于一小时,它应该显示 40 minutes ago 否则它应该显示 Today at 11:00Pm

需要输出

//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

编辑:

这是一个不依赖 3rd 方插件的版本,正如一些人在评论中指出的那样,Moment.js 现在维护时间更长,现代日期函数能够很好地处理这项工作自己的,当然,可能会有一些边缘情况需要考虑。

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 
    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>

原文Post:

所以基本上你只需要检查当前日期和按摩日期之间的差异。

Moment.js 有一个函数可以做到这一点。

获得差异后,您只需要一些 if else 块来为您的用例吐出正确的短语。

将所有内容包装在一个包含的函数中,您可以在需要它的任何项目中使用它。

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>

记得要开发还是要开发什么的。很大概率一个中国人已经做到了

安装 timeago.js

npm install timeago.js

只需在 Google 中查找即可。 PD:我无意冒犯任何人,这是事实