Link to home
Create AccountLog in
Avatar of dws02432
dws02432Flag for United States of America

asked on

How do I use TimeSpan in calculations across midnight

How do I use the C# TimeSpan in calculations that has ranges that cross midnight?  I have the following code that works like I need it too, except for when it needs to cross midnight.

TimeSpan start = new TimeSpan(23,30,0); //11:30pm
TimeSpan end = new TimeSpace(0,0,0); //12:00 am
TimeSpan now = DateTime.Now.TimeOfDay;

if ((now  >= start)  && (now <= end))
{
     // do something
}
SOLUTION
Avatar of Kyle Abrahams, PMP
Kyle Abrahams, PMP
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
ASKER CERTIFIED SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
Avatar of dws02432

ASKER

Thanks. Your tips/answer worked.  I wound up using the absolute times as suggested.  This is what I changed the TimeSpan option to:

DateTime rightNow = DateTime.Now;
DateTime start = new DateTime(rightNow,Year,rightNow.Month,rightNow.Day,23,30,0); //11:30pm
DateTime end = new DateTime(rightNow,Year,rightNow.Month,rightNow.Day,0,0,0); //12:00 am
DateTime now = DateTime.Now.TimeOfDay;

if (end < start_
 end.AddDays(1);

if ((now  >= start)  && (now <= end))
{
     // do something
}
To Idle_Mind, yeah I noticed that you couldn't use AddDays with the TimeSpan object.  But,then I noticed that ged325 had recommended using the absolute times, which would also work instead of using theTimeSpan object.

Thanks for the additional solution using the TimeSpan object.
See my answer...   =)

I think it's cleaner to declare the TimeSpan since it's easier to understand and modify in the future, then add that to a DateTime.

Also see kaufmed's  comment about AddDays() not being "in-place".  You need to assign the result of AddDays() back to your variable to replace it.
Thanks for the help!    Thoughtful knowledgeable answers, and quick response.  Greatly appreciated!