Home > Mobile >  Dynamically get difference between DateTime.Now and a model DateTime in Razor pages
Dynamically get difference between DateTime.Now and a model DateTime in Razor pages

Time:02-08

I'm using c# .NET razor pages and trying to dynamically change the 'minutes ago' count.

Basically, I have this code:

@foreach(var comment in Model.Comments)
            {
                TimeSpan timeSpan = (DateTime.Now - comment.CommentDate);
                int minutesAgo = Convert.ToInt32(timeSpan.TotalMinutes);

                <div>
                    <p>@comment.Message</p>
                    <span>@minutesAgo minutes ago</span>
                </div> 
            }

The calculation works, but it stays static on the page. I'm trying to get it updated as long the user stays on the page.

CodePudding user response:

The calculation works, but it stays static on the page.

The fastest way is you can use js to aoto refresh the page to make the time update.

@foreach(var comment in Model.Comments)
{
       TimeSpan timeSpan = (DateTime.Now - comment.CommentDate);
       int minutesAgo = Convert.ToInt32(timeSpan.TotalMinutes);
       <div>
            <p>@comment.Message</p>
            <span>@minutesAgo minutes ago</span>
       </div> 
}
@section Scripts
{
    
    <script type="text/javascript">
        //recall the page every one minute.....
        window.setTimeout(function () {
            window.location.href = "/Index";   //the href depend on yourself...
        //or just reload the page...
        //window.location.reload();
        }, 1000*60);
    </script>
}

CodePudding user response:

One way of do this is use html data attribute and a js function to update the displayed text. Something like this:


<div >
    <span  data-datetime="@DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss")"></span>
</div>

<script type="text/javascript">
    //recall the page every one minute.....
    function update_call() {
        var dtus = document.getElementsByClassName('dtu');
        Array.prototype.every.call(dtus, function(el) {
            const dtPost = new Date(el.dataset.datetime);
            el.innerHTML = timeAgo(dtPost);
        });
        window.setTimeout(update_call, 1000*5);
    }
    window.setTimeout(update_call, 500);

    const MONTH_NAMES = [
        'January', 'February', 'March', 'April', 'May', 'June',
        'July', 'August', 'September', 'October', 'November', 'December'
    ];

    function getFormattedDate(date, prefomattedDate = false, hideYear = false) {
    const day = date.getDate();
    const month = MONTH_NAMES[date.getMonth()];
    const year = date.getFullYear();
    const hours = date.getHours();
    let minutes = date.getMinutes();

    if (minutes < 10) {
        // Adding leading zero to minutes
        minutes = `0${ minutes }`;
    }

    if (prefomattedDate) {
        // Today at 10:20
        // Yesterday at 10:20
        return `${ prefomattedDate } at ${ hours }:${ minutes }`;
    }

    if (hideYear) {
        // 10. January at 10:20
        return `${ day }. ${ month } at ${ hours }:${ minutes }`;
    }

    // 10. January 2017. at 10:20
    return `${ day }. ${ month } ${ year }. at ${ hours }:${ minutes }`;
    }


    // --- Main function
    function timeAgo(dateParam) {
    if (!dateParam) {
        return null;
    }

    const date = typeof dateParam === 'object' ? dateParam : new Date(dateParam);
    const DAY_IN_MS = 86400000; // 24 * 60 * 60 * 1000

    var todayDate = new Date(); 
    var now_utc =  Date.UTC(todayDate.getUTCFullYear(), todayDate.getUTCMonth(), todayDate.getUTCDate(), todayDate.getUTCHours(), todayDate.getUTCMinutes(), todayDate.getUTCSeconds());
    const today = new Date(now_utc);
    const yesterday = new Date(today - DAY_IN_MS);
    const seconds = Math.round((today - date) / 1000);
    const minutes = Math.round(seconds / 60);
    const isToday = today.toDateString() === date.toDateString();
    const isYesterday = yesterday.toDateString() === date.toDateString();
    const isThisYear = today.getFullYear() === date.getFullYear();


    if (seconds < 5) {
        return 'now';
    } else if (seconds < 60) {
        return `${ seconds } seconds ago`;
    } else if (seconds < 90) {
        return 'about a minute ago';
    } else if (minutes < 60) {
        return `${ minutes } minutes ago`;
    } else if (isToday) {
        return getFormattedDate(date, 'Today'); // Today at 10:20
    } else if (isYesterday) {
        return getFormattedDate(date, 'Yesterday'); // Yesterday at 10:20
    } else if (isThisYear) {
        return getFormattedDate(date, false, true); // 10. January at 10:20
    }

    return getFormattedDate(date); // 10. January 2017. at 10:20
    }
</script>
  •  Tags:  
  • Related