Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Total days between two dates and round up

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

like image 936
Paramone Avatar asked Jan 03 '23 03:01

Paramone


1 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)

like image 120
Tim Schmelter Avatar answered Jan 13 '23 12:01

Tim Schmelter