Pradeep Singh
Pradeep Singh

Reputation: 243

Compare DateTime.Now to exact time

I want to have exact time of the day on the timer elapsed event Below is what I am trying to do

    string now = DateTime.Now.ToString("HHmm");

        if (now == "1630")
        {
            int a = 10;
        }

even when the time is 1630 the if statement is false,What am I doing Wrong here.

Upvotes: 2

Views: 676

Answers (3)

Andrey Gordeev
Andrey Gordeev

Reputation: 32449

No idea why you convert current time to string

DateTime currentTime = DateTime.Now;
if (currentTime.Hour == 16 && currentTime.Minute == 30)
{
     int a = 10;
}

Upvotes: 10

Talha
Talha

Reputation: 19252

TimeSpan dbaseTime = TimeSpan.Parse("16:30:00");
if (DateTime.Now.TimeOfDay == dbaseTime )
   a=10;

Upvotes: 1

sajanyamaha
sajanyamaha

Reputation: 3198

Avoid converting time to string ,Do somrthing like this

if(DateTime.Now.TimeOfDay == System.TimeSpan.Parse("00:09:00"))
{
 int a = 10;
}

Upvotes: 1

Related Questions