Calculate relative time in C#

后端 未结 30 2133
生来不讨喜
生来不讨喜 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:29

    If you want to have an output like "2 days, 4 hours and 12 minutes ago", you need a timespan:

    TimeSpan timeDiff = DateTime.Now-CreatedDate;
    

    Then you can access the values you like:

    timeDiff.Days
    timeDiff.Hours
    

    etc...

提交回复
热议问题