Calculate relative time in C#

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

    @Jeff

    var ts = new TimeSpan(DateTime.UtcNow.Ticks - dt.Ticks);
    

    Doing a subtraction on DateTime returns a TimeSpan anyway.

    So you can just do

    (DateTime.UtcNow - dt).TotalSeconds
    

    I'm also surprised to see the constants multiplied-out by hand and then comments added with the multiplications in. Was that some misguided optimisation?

提交回复
热议问题