给定特定的DateTime值,如何显示相对时间,例如:

2小时前3天前一个月前


当前回答

文斯回答的土耳其语本地化版本。

    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 < 1 * MINUTE)
        return ts.Seconds + " saniye önce";

    if (delta < 45 * MINUTE)
        return ts.Minutes + " dakika önce";

    if (delta < 24 * HOUR)
        return ts.Hours + " saat önce";

    if (delta < 48 * HOUR)
        return "dün";

    if (delta < 30 * DAY)
        return ts.Days + " gün önce";

    if (delta < 12 * MONTH)
    {
        int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
        return months + " ay önce";
    }
    else
    {
        int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
        return years + " yıl önce";
    }

其他回答

/** 
 * {@code date1} has to be earlier than {@code date2}.
 */
public static String relativize(Date date1, Date date2) {
    assert date2.getTime() >= date1.getTime();

    long duration = date2.getTime() - date1.getTime();
    long converted;

    if ((converted = TimeUnit.MILLISECONDS.toDays(duration)) > 0) {
        return String.format("%d %s ago", converted, converted == 1 ? "day" : "days");
    } else if ((converted = TimeUnit.MILLISECONDS.toHours(duration)) > 0) {
        return String.format("%d %s ago", converted, converted == 1 ? "hour" : "hours");
    } else if ((converted = TimeUnit.MILLISECONDS.toMinutes(duration)) > 0) {
        return String.format("%d %s ago", converted, converted == 1 ? "minute" : "minutes");
    } else if ((converted = TimeUnit.MILLISECONDS.toSeconds(duration)) > 0) {
        return String.format("%d %s ago", converted, converted == 1 ? "second" : "seconds");
    } else {
        return "just now";
    }
}

通过在客户端执行此逻辑,可以减少服务器端负载。在一些Digg页面上查看源代码以供参考。它们让服务器发出一个由Javascript处理的历元时间值。这样,您就不需要管理最终用户的时区。新的服务器端代码类似于:

public string GetRelativeTime(DateTime timeStamp)
{
    return string.Format("<script>printdate({0});</script>", timeStamp.ToFileTimeUtc());
}

您甚至可以在那里添加一个NOSCRIPT块,然后执行ToString()。

文森特接受的答案做出了许多武断的决定。为什么45分钟舍入为一小时,而45秒不舍入为一分钟?在年和月的计算中,它的圈复杂度增加了,这使得遵循逻辑变得更加复杂。它假设TimeSpan是相对于过去(2天前)的,而它很可能是在未来(2天后)。它定义了不必要的常量,而不是使用TimeSpan.TicksPerSecond等。

此实现解决了上述问题,并更新了语法以使用开关表达式和关系模式

/// <summary>
/// Convert a <see cref="TimeSpan"/> to a natural language representation.
/// </summary>
/// <example>
/// <code>
/// TimeSpan.FromSeconds(10).ToNaturalLanguage();
/// // 10 seconds
/// </code>
/// </example>
public static string ToNaturalLanguage(this TimeSpan @this)
{
    const int daysInWeek = 7;
    const int daysInMonth = 30;
    const int daysInYear = 365;
    const long threshold = 100 * TimeSpan.TicksPerMillisecond;
    @this = @this.TotalSeconds < 0
        ? TimeSpan.FromSeconds(@this.TotalSeconds * -1)
        : @this;
    return (@this.Ticks + threshold) switch
    {
        < 2 * TimeSpan.TicksPerSecond => "a second",
        < 1 * TimeSpan.TicksPerMinute => @this.Seconds + " seconds",
        < 2 * TimeSpan.TicksPerMinute => "a minute",
        < 1 * TimeSpan.TicksPerHour => @this.Minutes + " minutes",
        < 2 * TimeSpan.TicksPerHour => "an hour",
        < 1 * TimeSpan.TicksPerDay => @this.Hours + " hours",
        < 2 * TimeSpan.TicksPerDay => "a day",
        < 1 * daysInWeek * TimeSpan.TicksPerDay => @this.Days + " days",
        < 2 * daysInWeek * TimeSpan.TicksPerDay => "a week",
        < 1 * daysInMonth * TimeSpan.TicksPerDay => (@this.Days / daysInWeek).ToString("F0") + " weeks",
        < 2 * daysInMonth * TimeSpan.TicksPerDay => "a month",
        < 1 * daysInYear * TimeSpan.TicksPerDay => (@this.Days / daysInMonth).ToString("F0") + " months",
        < 2 * daysInYear * TimeSpan.TicksPerDay => "a year",
        _ => (@this.Days / daysInYear).ToString("F0") + " years"
    };
}

/// <summary>
/// Convert a <see cref="DateTime"/> to a natural language representation.
/// </summary>
/// <example>
/// <code>
/// (DateTime.Now - TimeSpan.FromSeconds(10)).ToNaturalLanguage()
/// // 10 seconds ago
/// </code>
/// </example>
public static string ToNaturalLanguage(this DateTime @this)
{
    TimeSpan timeSpan = @this - DateTime.Now;
    return timeSpan.TotalSeconds switch
    {
        >= 1 => timeSpan.ToNaturalLanguage() + " until",
        <= -1 => timeSpan.ToNaturalLanguage() + " ago",
        _ => "now",
    };
}

可以使用NUnit对其进行如下测试:

[TestCase("a second", 0)]
[TestCase("a second", 1)]
[TestCase("2 seconds", 2)]
[TestCase("a minute", 0, 1)]
[TestCase("5 minutes", 0, 5)]
[TestCase("an hour", 0, 0, 1)]
[TestCase("2 hours", 0, 0, 2)]
[TestCase("a day", 0, 0, 24)]
[TestCase("a day", 0, 0, 0, 1)]
[TestCase("6 days", 0, 0, 0, 6)]
[TestCase("a week", 0, 0, 0, 7)]
[TestCase("4 weeks", 0, 0, 0, 29)]
[TestCase("a month", 0, 0, 0, 30)]
[TestCase("6 months", 0, 0, 0, 6 * 30)]
[TestCase("a year", 0, 0, 0, 365)]
[TestCase("68 years", int.MaxValue)]
public void NaturalLanguageHelpers_TimeSpan(
    string expected,
    int seconds,
    int minutes = 0,
    int hours = 0,
    int days = 0
)
{
    // Arrange
    TimeSpan timeSpan = new(days, hours, minutes, seconds);

    // Act
    string result = timeSpan.ToNaturalLanguage();

    // Assert
    Assert.That(result, Is.EqualTo(expected));
}

[TestCase("now", 0)]
[TestCase("10 minutes ago", 0, -10)]
[TestCase("10 minutes until", 10, 10)]
[TestCase("68 years until", int.MaxValue)]
[TestCase("68 years ago", int.MinValue)]
public void NaturalLanguageHelpers_DateTime(
    string expected,
    int seconds,
    int minutes = 0,
    int hours = 0,
    int days = 0
)
{
    // Arrange
    TimeSpan timeSpan = new(days, hours, minutes, seconds);
    DateTime now = DateTime.Now;
    DateTime dateTime = now + timeSpan;

    // Act
    string result = dateTime.ToNaturalLanguage();

    // Assert
    Assert.That(result, Is.EqualTo(expected));
}

或者作为要点:https://gist.github.com/StudioLE/2dd394e3f792e79adc927ede274df56e

// Calculate total days in current year
int daysInYear;

for (var i = 1; i <= 12; i++)
    daysInYear += DateTime.DaysInMonth(DateTime.Now.Year, i);

// Past date
DateTime dateToCompare = DateTime.Now.Subtract(TimeSpan.FromMinutes(582));

// Calculate difference between current date and past date
double diff = (DateTime.Now - dateToCompare).TotalMilliseconds;

TimeSpan ts = TimeSpan.FromMilliseconds(diff);

var years = ts.TotalDays / daysInYear; // Years
var months = ts.TotalDays / (daysInYear / (double)12); // Months
var weeks = ts.TotalDays / 7; // Weeks
var days = ts.TotalDays; // Days
var hours = ts.TotalHours; // Hours
var minutes = ts.TotalMinutes; // Minutes
var seconds = ts.TotalSeconds; // Seconds

if (years >= 1)
    Console.WriteLine(Math.Round(years, 0) + " year(s) ago");
else if (months >= 1)
    Console.WriteLine(Math.Round(months, 0) + " month(s) ago");
else if (weeks >= 1)
    Console.WriteLine(Math.Round(weeks, 0) + " week(s) ago");
else if (days >= 1)
    Console.WriteLine(Math.Round(days, 0) + " days(s) ago");
else if (hours >= 1)
    Console.WriteLine(Math.Round(hours, 0) + " hour(s) ago");
else if (minutes >= 1)
    Console.WriteLine(Math.Round(minutes, 0) + " minute(s) ago");
else if (seconds >= 1)
    Console.WriteLine(Math.Round(seconds, 0) + " second(s) ago");

Console.ReadLine();

如果您想获得类似“2天4小时12分钟前”的输出,则需要一个时间跨度:

TimeSpan timeDiff = DateTime.Now-CreatedDate;

然后您可以访问您喜欢的值:

timeDiff.Days
timeDiff.Hours