Calculate relative time in C#

后端 未结 30 2121
生来不讨喜
生来不讨喜 2020-11-21 05:59

Given a specific DateTime value, how do I display relative time, like:

  • 2 hours ago
  • 3 days ago
  • a month ago
30条回答
  •  不思量自难忘°
    2020-11-21 06:16

    There are also a package called Humanizr on Nuget, and it actually works really well, and is in the .NET Foundation.

    DateTime.UtcNow.AddHours(-30).Humanize() => "yesterday"
    DateTime.UtcNow.AddHours(-2).Humanize() => "2 hours ago"
    
    DateTime.UtcNow.AddHours(30).Humanize() => "tomorrow"
    DateTime.UtcNow.AddHours(2).Humanize() => "2 hours from now"
    
    TimeSpan.FromMilliseconds(1299630020).Humanize() => "2 weeks"
    TimeSpan.FromMilliseconds(1299630020).Humanize(3) => "2 weeks, 1 day, 1 hour"
    

    Scott Hanselman has a writeup on it on his blog

提交回复
热议问题