如何比较一个DateTime数据的时间部分是否在另外两个DateTime之间? ( 积分: 300 )

Y

yu_ting

Unregistered / Unconfirmed
GUEST, unregistred user!
我是这样做的:
public static bool BetweenTime(DateTime time1, DateTime time, DateTime time2)
{
return ((time.TimeOfDay >= time1.TimeOfDay) &&
(time.TimeOfDay <= time2.TimeOfDay));
}
我只需要精确到秒就可以了,但是返回的结果不正确,好像TimeOfDay是精确到毫秒的,但参数time只能精确到秒.各位有什么好办法?
 
我是这样做的:
public static bool BetweenTime(DateTime time1, DateTime time, DateTime time2)
{
return ((time.TimeOfDay >= time1.TimeOfDay) &amp;&amp;
(time.TimeOfDay <= time2.TimeOfDay));
}
我只需要精确到秒就可以了,但是返回的结果不正确,好像TimeOfDay是精确到毫秒的,但参数time只能精确到秒.各位有什么好办法?
 
由于日期型是用浮点数表示的,因此你的参数可以用浮点类型传递,这样可以保证精度。
 
判断A>B且A<C,然后返回1,否则返回0。这样不行啊??
 
直接比较大小就可以了
时间日期本身就是一个do
uble 类型啊
问这个问题用300分?
 
但是人工操作的时候,精确度要低好多,除非系统自动判断,否则若是人为操作的话,可以不用那么精确吧。
 
不是了,关键是个精度的问题,TimeSpan的精确到毫秒,三个形参time1,time,time2在实参中time1,time2只能精确到秒,而time则精确到毫秒,我只需要比较到秒就可以了,可毫秒就不知道如何处理了,本人对C#玩的不咋的,要是用pascal就不在话下了.各位帮帮忙呀!
 
没用过c#,有没有time.secondofDay啊?
 
把它轉換為字符串就是精確到秒。或者利用日期函數把小時分鐘秒全部轉化為秒再計算。
其它就沒什么好方法了。好象沒有比較時間大小精確到秒的函數
 
uses DateUtils
function SecondsBetween(const ANow, Athen
: TDateTime): Int64;
 
use
...,dateutils;
var
dt1,dt2,dt3:tdatetime;
begin
...
if (timeof(dt1)>=timeof(dt2)) and (timeof(dt1)<timeof(dt3)) then
//dt1 在dt2和dt3之间
else

//dt1 不在dt2和dt3之间
 
好像这个可以直接比较吧。
t1 := now;
sleep(1000);
t2 := now;
sleep(1000);
t3 := now;
if (t2 > t1) and (t2 < t3) then
ShowMessage('asd');
刚测试结果似乎没有问题啊
 
楼主的是C#,大家搞错了
 
Visual Basic 语言参考
TimeOfDay 属性
返回或设置 Date 值,该值包含与系统对应的当前时间。
Public Property TimeOfDay() As DateTime
备注
Date 数据类型包含日期组件。返回系统时间时,TimeOfDay 将这些组件都设置为 1,以使返回的值表示元年的第一天。设置系统时间时,TimeOfDay 忽略日期组件。
要把当前系统时间当作 String 来访问,请使用 TimeString 属性。
要获取或设置当前系统日期,请使用 Today 属性。
示例
本示例使用 TimeOfDay 属性返回系统当前时间。
Dim MyTime As Date
MyTime = TimeOfDay ' Return current system time.
要求
命名空间:Microsoft.VisualBasic
模块:DateAndTime
程序集:Microsoft Visual Basic .NET 运行库(位于 Microsoft.VisualBasic.dll 中)
由于 TimeOfDay 是模块的成员,而不是类的成员,因此不需要创建用来访问 TimeOfDay 的对象。
请参见
Timer 属性 | TimeString 属性 | Today 属性 | System 命名空间 | DateTime 结构 | ArgumentException 类 | ArgumentOutOfRangeException 类

显然精度不够
 
public static bool BetweenTime(DateTime minTime, DateTime maxTime, DateTime theTime)
{
return (int)(theTime-minTime).TotalSeconds>=0 &amp;&amp;
(int)(theTime-maxTime).TotalSeconds<=0;
}
精确到秒.
 
来迟了,楼上正解!
public static bool BetweenTime(DateTime minTime, DateTime maxTime, DateTime theTime)
{
return (int)(theTime-minTime).TotalSeconds>=0 &amp;&amp;
(int)(theTime-maxTime).TotalSeconds<=0;
}
 
见者有分
 
见者有分
 

Similar threads

S
回复
0
查看
3K
SUNSTONE的Delphi笔记
S
S
回复
0
查看
2K
SUNSTONE的Delphi笔记
S
I
回复
0
查看
630
import
I
顶部