Home > front end >  ASP.NET C# Countdown to end of offer - Razor View
ASP.NET C# Countdown to end of offer - Razor View

Time:11-28

I want to have on my web app something like a "timer" to end of my work order. If I add new job everything looks good, for example: DateOfWorkCompletion is tomorrow, then the work list shows communicate "end of offer in @TimeToEnd day", but if tomorrow comes, and I refresh page the text is still the same. Why? What should I do?

var TimeToEnd = Math.Floor(decimal.Parse((DateTime.Today - work.DateOfWorkCompletion).Value.ToString("dd")));
    <h2>
        @Html.ActionLink(work.Name, "Details", new { work.WorkId }, new { style = "text-decoration: none; color:black;" })
            <span class="timeAlert">
                -
                @if (TimeToEnd > 1)
                {
                    <span>end of offer in @TimeToEnd days/span> 
                }
                else if (TimeToEnd == 0)
                { 
                    <span class="text-danger">the offer ends today</span>
                }
                else if (TimeToEnd == 1)
                {
                    <span class="text-danger">end of offer in @TimeToEnd day</span>
                else
                { 
                    <span class="text-danger">offer has expired</span>
                }

CodePudding user response:

If the work.DateOfWorkCompletion is in the future, then doing DateTime.Today - work.DateOfWorkCompletion will result in a negative value.. You then throw in the confusion that ToStringing the days in a negative timespan results in a positive value

Ditch all that to-ing and fro-ing with string: one date minus another date results in a TimeSpan, and TimeSpan has properties you can inspect that reveal info about the length of the time period between the two dates.

Personally, I'd recommend to use timed datetimes too, if e.g. the offer finishes at 6pm tomorrow, and it's 3pm today, then there is 1 day and 3h left til the offer expires:

var tsTilExpiry = someFutureDate - DateTime.Now; //results in a TimeSpan

Console.WriteLine("Offer ends in: "   tsTilExpiry);
Console.WriteLine($"Offer ends in {tsTilExpiry.TotalMinutes} minutes");

Console.WriteLine($"Offer ends in {tsTilExpiry.Days} days, {tsTilExpiry.Hours} hours");


if(tsTilExpiry.TotalDays < 1)
  Console.WriteLine("Hurry! Offer finishes in less than a day");
  • Related