0

I'm here to ask more how to do something rather than check my mistakes.

I have a value

public virtual DateTime DateCreated { get; set; }

And I show it in the view like this:

asked @item.DateCreated by @item.Creator.FullName

which gives this

asked 2/2/2018 2:28:13 PM by System Administrator

I would like to do it like in StackOverflow

asked 5mins ago by x

What would your suggestions be for doing that? I'd need some code example, that's why I'm writing in SO, not SE.

  • Calculate it based on the value of `DateTime.Now` - e.g. `double duration = (DateTime.Now - DateCreated).TotalMinutes;` But you need to consider what happens when that's a large number - does it become `x hours and y minutes ago` or `x days` ago. And then you need to consider using a javascript timer to update it in the view (in the same way SO does it - e.g. the 'asked x mins ago' that you see above your name in this question) –  Feb 09 '18 at 07:56
  • 1
    Possible duplicate of [Javascript timestamp to relative time (eg 2 seconds ago, one week ago etc), best methods?](https://stackoverflow.com/questions/6108819/javascript-timestamp-to-relative-time-eg-2-seconds-ago-one-week-ago-etc-best) – thmshd Feb 09 '18 at 08:23
  • Most people use JavaScript, the big advantage is that it does that it updates in "real time" in the browser. We're using [TimeAgo](http://timeago.yarp.com/) for that – thmshd Feb 09 '18 at 08:25
  • @thmshd do I have to change the model though? because .NET uses a different standard for time? –  Feb 09 '18 at 08:39
  • No, you don't need to change the model if you want to use the JavaScript solution. You just need to convert the `DateCreated` value to a JavaScript date value. If you prefer to do it in C#, then you can use my answer, which also doesn't require changing your model if you don't want it. – Racil Hilan Feb 09 '18 at 08:52
  • I think I'll use the TimeAgo library. Makes things way easier. But thanks for the answer. –  Feb 09 '18 at 09:09

1 Answers1

0

You can do it this way:

@{
    var diff = DateTime.Now.Subtract(DateCreated);
    var result = diff.TotalSeconds;
    var unit = "seconds";
    if (result >= 60) {
        result = diff.TotalMinutes;
        unit = "minutes";

        if (result >= 60) {
            result = diff.TotalHours;
            unit = "hours";
        }
    }
}

asked @result @unit by @item.Creator.FullName

If you need to support more unites like days, then add more if blocks, but you get the idea.

You can put this code in code-behind and probably make the result and unit as properties of the item object.

Racil Hilan
  • 24,690
  • 13
  • 50
  • 55