将日期转换为可读性更强的格式

Converting dates to a more readable format

本文关键字:格式 可读性 日期 转换      更新时间:2024-06-18

给定从现在到未来7天随机选择的DateTime值数组,我如何显示相对时间值,如:

  • 2小时内
  • 第3天
  • 在1米内

目前,我的程序生成了一个随机dateArray,其中包含以下格式的项,理想情况下,我希望将其传递到一个函数中,该函数将以相对时间格式返回它们。

var timelineItemCount = getRandomInt(0, 19);
var dateArray = new Array();
    for(i=0;i<timelineItemCount;i++)
    {
        var today = new Date();
        var randomDates = randomDate(today, new Date(today.getFullYear(), today.getMonth(), today.getDate()+7));
        dateArray.push(randomDates);
    }   
    dateArray.sort(function compare(a, B)/> {
        return (a < B)/> - (a > B)/>;
    });
    console.log(dateArray);
function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
function randomDate(start, end) {
    return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
}

我做了一些研究,到目前为止,我看到了如何用过去的值计算相对时间的例子,但我还没有看到太多从现在到未来7天之间选择的值。例如:

const int SECOND = 1;
const int MINUTE = 60 * SECOND;
const int HOUR = 60 * MINUTE;
const int DAY = 24 * HOUR;
const int MONTH = 30 * DAY;
var ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks);
double delta = Math.Abs(ts.TotalSeconds);
if (delta < 0)
{
  return "not yet";
}
if (delta < 1 * MINUTE)
{
  return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";
}
if (delta < 2 * MINUTE)
{
  return "a minute ago";
}
if (delta < 45 * MINUTE)
{
  return ts.Minutes + " minutes ago";
}
if (delta < 90 * MINUTE)
{
  return "an hour ago";
}
if (delta < 24 * HOUR)
{
  return ts.Hours + " hours ago";
}
if (delta < 48 * HOUR)
{
  return "yesterday";
}
if (delta < 30 * DAY)
{
  return ts.Days + " days ago";
}
if (delta < 12 * MONTH)
{
  int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
  return months <= 1 ? "one month ago" : months + " months ago";
}
else
{
  int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
  return years <= 1 ? "one year ago" : years + " years ago";
}

您可以编写自己的lib来完成它,也可以使用现有的lib:

  • moment.js:http://momentjs.com/
  • 时间:http://timeago.yarp.com/