0

I want to create a method it returns string and (calculate the period expires days) differences between expires date and current date.

  • if the differences is less than 1 minutes i will return in second ex: 8 seconds

  • if the differences is less than 1 hours i will return in minutes ex: 28 minutes

  • if the differences is less than 24 (a day) hours i will return in hours ex: 7 hours

  • default if not matches any case I will return days ex: 3 days

what I have already tried is

(item.EndDate- DateTime.Today).Days

But is does not work when the difference less than 24 hours it will return 0.

Can you give me suggestion?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Joseph
  • 35
  • 6

3 Answers3

1

To answer the original question

when the difference less than 24 hours it will return 0 can you give me suggestion?

You can use TotalDays;

double ds = ((d1-d2).TotalDays;
tymtam
  • 31,798
  • 8
  • 86
  • 126
0

You should check your expiration time starting by biggest value (which in your question it's a day). First write your method like below:

public static string CalculateExpirationTime(DateTime expiryDate)
{
    var currentDate = DateTime.Now;
    var dateDifference = (expiryDate - currentDate);

    if (dateDifference.Days >= 1)
        return $"{ dateDifference.Days } day(s) remained";
    else if (dateDifference.Hours >= 1)
        return $"{ dateDifference.Hours } hour(s) remained";
    else if (dateDifference.Minutes >= 1)
        return $"{ dateDifference.Minutes } minute(s) remained";
    else if (dateDifference.TotalSeconds >= 1)
        return $"{ dateDifference.Seconds } second(s) remained";

    return "Expired!";
}

And then call it this way:

string status = CalculateExpirationTime(item.EndDate);
itsMasoud
  • 1,335
  • 2
  • 9
  • 25
0
DateTime biggerDate;  // pretend it has some valid value
DateTime smallDate;  //     ditto

TimeSpan datesDiff = biggerDate - smallDate;  // assume a positive diff.

if (dateDiff.TotalMinutes < 1) {return new TimeSpan(0,0,0,8);} else
if (dateDiff.TotalHours < 1)   {return new TimeSpan(0,0,28);} else
if (dateDiff.TotalDays < 1)    {return new TimeSpan(0,7,0);} else
return new TimeSpan(3,0,0);  

------------- or ? --------------

if (dateDiff.TotalMinutes < 1) {return dateDiff.TotalSeconds;} else
if (dateDiff.TotalHours < 1)   {return dateDiff.TotalMinutes;} else
if (dateDiff.TotalDays < 1)    {return dateDiff.TotalHours} else
return dateDiff.TotalDays;

-

radarbob
  • 4,964
  • 2
  • 23
  • 36