How to extract time only from DateTime.Now, and compare it with

  • Thread starter Thread starter Curious
  • Start date Start date
C

Curious

I have code below. But it won't compile.
Error:

Cannot implicitly convert type 'System.TimeSpan' to 'System.DateTime'

DateTime now = DateTime.Now.TimeOfDay;

DateTime openTime = Convert.ToDateTime("9:30:00");

if (now < openTime)
{
// Do nothing if it's before 9:30 AM
return;
}
 
Curious said:
I have code below. But it won't compile.
Error:

Cannot implicitly convert type 'System.TimeSpan' to 'System.DateTime'

DateTime now = DateTime.Now.TimeOfDay;

DateTime openTime = Convert.ToDateTime("9:30:00");

if (now < openTime)
{
// Do nothing if it's before 9:30 AM
return;
}

TimeOfDay returns a TimeSpan and you're assigning it to a DateTime. Try:

TimeSpan now = DateTime.Now.TimeOfDay;

TimeSpan openTime = TimeSpan.Parse("0.09:30:00");

if (now < openTime)
{
return;
}
 
Thanks John!

It works! Could you tell me why you use TimeSpan.Parse("0.09:30:00")
instead of TimeSpan.Parse("9:30:00") ?
 
Curious said:
Thanks John!

It works! Could you tell me why you use TimeSpan.Parse("0.09:30:00")
instead of TimeSpan.Parse("9:30:00") ?

The leading "0." is the number of days in the TimeSpan, I just included it
to have a complete specification.
 
Back
Top