C#控制循环中的时间比较 [英] C# controlling the time comparison in loop

查看:71
本文介绍了C#控制循环中的时间比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,



我给我的代码打了一小部分。我的问题是当我运行这段代码时,我总是得到假。我该如何解决这个问题?



Hello,

I give my code snipple down part.My problem is when i run this code i get false all time. How can i fix this?

While(!isStop)
{
	var isReportOnly = false;
	var isInReportPeriod = false;

	DateTime dtStart = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 22, 0, 0);
	DateTime dtStop = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 06, 0, 0);
	if (DateTime.Now > dtStart && DateTime.Now < dtStop)
	{
		isInReportPeriod = true;
		log.Add( DateTime.Now.ToString() + "=True\n");
	}
	else
	{
		isInReportPeriod = false;
		log.Add(DateTime.Now.ToString() + "=False\n");
	}
}





我的尝试:



我如何解决循环中的时间问题



What I have tried:

How can i fix the problem for time comprison in the loop

推荐答案

嗯。

开始时间是22:00,停止时间是06:00。

要记录TRUE,您需要当天时间在22:00之后和当天06:00之前...



可能你的开始和停止时间错了吗?



但不要这样做:永远不会多次读取时间,它可能会在白天,(或更糟的月份或年份)变化时引起问题。



Um.
Start is 22:00, stop is 06:00.
To log TRUE, you need the current time to be both after 22:00 and before 06:00 on the same day...

Possibly you got the start and stop times wrong?

But don't do it like that anyway: never read the time more than once, it can cause problems when the day, (or worse month or year) changes.

DateTime now = DatetIme.Now;
DateTime start = now.Date.AddHours(6);
DateTime stop = now.Date.AddHours(22);
if (now > start && now < stop)
   {
   ...


这篇关于C#控制循环中的时间比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆