Calculate relative time in C#

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

    I got this answer from one of Bill Gates' blogs. I need to find it on my browser history and I'll give you the link.

    The Javascript code to do the same thing (as requested):

    function posted(t) {
        var now = new Date();
        var diff = parseInt((now.getTime() - Date.parse(t)) / 1000);
        if (diff < 60) { return 'less than a minute ago'; }
        else if (diff < 120) { return 'about a minute ago'; }
        else if (diff < (2700)) { return (parseInt(diff / 60)).toString() + ' minutes ago'; }
        else if (diff < (5400)) { return 'about an hour ago'; }
        else if (diff < (86400)) { return 'about ' + (parseInt(diff / 3600)).toString() + ' hours ago'; }
        else if (diff < (172800)) { return '1 day ago'; } 
        else {return (parseInt(diff / 86400)).toString() + ' days ago'; }
    }
    

    Basically, you work in terms of seconds.

提交回复
热议问题