C# - Total days between two dates and round up

Viewed 1646

I'd like to make an option available if 'now' is two days past start date, but the option must still be valid until the end of the day.

So let's say something has been ordered on:

10-10-2017 15:00

The option must be visible on

12-10-2017 23:59

I used

if (ShippedDate.HasValue && (DateTime.Now - ShippedDate.Value).TotalDays <= 2)

However once 48 hours pass, (12-10-2017 15:01), it has returned false

I've tried comparing the days, but technically, you could always change it, as long as the (day-2) equals start date.

I'm sure there's a way simpler way of doing this, but I just can't get my mind on it.


Thanks for the super fast replies everyone. Ended up using Tim Schmelter's answer

6 Answers

You can use the Date and Today properties which truncate the time portion:

bool withinTwoDays = (DateTime.Today - ShippedDate?.Date)?.Days <= 2;

(I've also used the null-conditional-operator to avoid the null/HasValue check)

Try like this;

if (ShippedDate.HasValue && (DateTime.Now.Date - ShippedDate.Value.Date).TotalDays <= 2)

Just use Date property.

Change DateTime.Now to DateTime.Today

if (ShippedDate.HasValue && (DateTime.Today - ShippedDate.Value).TotalDays <= 2)
if (ShippedDate.HasValue && (DateTime.Now.Date - ShippedDate.Value.Date).TotalDays <= 2)
if (ShippedDate.HasValue && 
     (DateTime.Now - new DateTime(ShippedDate.Value.Year, 
     ShippedDate.Value.Month, ShippedDate.Value.Day, 23,59,59)).TotalDays <= 2)

At 15:01 on 12-10-2017 is will already past 48 hours, right ?

so, this condition

(DateTime.Now - ShippedDate.Value).TotalDays <= 2

will be false.

Related