简体   繁体   中英

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.

No idea why you convert current time to string

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

Avoid converting time to string ,Do somrthing like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM