dws02432
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
}
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
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
ASKER CERTIFIED SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
ASKER
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.
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.
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.
ASKER
Thanks for the help! Thoughtful knowledgeable answers, and quick response. Greatly appreciated!
ASKER
DateTime rightNow = DateTime.Now;
DateTime start = new DateTime(rightNow,Year,rig
DateTime end = new DateTime(rightNow,Year,rig
DateTime now = DateTime.Now.TimeOfDay;
if (end < start_
end.AddDays(1);
if ((now >= start) && (now <= end))
{
// do something
}