两个字符串时间和现在的区别

时间:2022-03-19 21:31:59

I have a string like that 03223311 (hhmmssff). I'm going to compare it with DateTime.Now and see if the difference between these to values is lower than 200 miliseconds.

我有一个像03223311(hhmmssff)的字符串。我要将它与DateTime.Now进行比较,看看这些值之间的差异是否低于200毫秒。

   xdate="03223311";

   if(Math.Abs(Convert.ToInt32(xdate) - Convert.ToInt32(DateTime.Now.ToString("hhmmssff")))<200)

I tried to run the line above in a timer with interval of 1 but I can not reach to that condition even if I change xdate to current time... . Do you know how to solve the problem or even a better approach?

我尝试在间隔为1的计时器中运行上面的行,但即使我将xdate更改为当前时间,我也无法达到该条件。你知道如何解决问题甚至更好的方法吗?

3 个解决方案

#1


3  

string input = "03223311";

var diff = DateTime.Now.TimeOfDay.Subtract(
                TimeSpan.ParseExact(input, "hhmmssff", null)
           ).TotalMinutes; //or any other value like TotalMilliseconds

#2


2  

I would first convert the string into a DateTime so that you can compare apples to apples and utilized the features of the DateTime object. Once you have two DateTime objects, you can subtract them to get a TimeSpan. TimeSpan will have a TotalMilliseconds property that you can compare to your 200 constant.

我首先将字符串转换为DateTime,以便您可以比较苹果和苹果,并利用DateTime对象的功能。一旦有两个DateTime对象,就可以减去它们以获得TimeSpan。 TimeSpan将具有TotalMilliseconds属性,您可以将其与200常量进行比较。

var xdateValue = DateTime.ParseExact(xdate, "hhmmssff", CultureInfo.InvariantCulture);
var difference = DateTime.Now - xdateValue;
if (difference.TotalMilliseconds < 200) ...

#3


1  

if (((DatetTime.Now - DateTime.ParseExact("03223311 ", "hhmmssff", CultureInfo.InvariantCulture))).Milliseconds > 200)
{

}

#1


3  

string input = "03223311";

var diff = DateTime.Now.TimeOfDay.Subtract(
                TimeSpan.ParseExact(input, "hhmmssff", null)
           ).TotalMinutes; //or any other value like TotalMilliseconds

#2


2  

I would first convert the string into a DateTime so that you can compare apples to apples and utilized the features of the DateTime object. Once you have two DateTime objects, you can subtract them to get a TimeSpan. TimeSpan will have a TotalMilliseconds property that you can compare to your 200 constant.

我首先将字符串转换为DateTime,以便您可以比较苹果和苹果,并利用DateTime对象的功能。一旦有两个DateTime对象,就可以减去它们以获得TimeSpan。 TimeSpan将具有TotalMilliseconds属性,您可以将其与200常量进行比较。

var xdateValue = DateTime.ParseExact(xdate, "hhmmssff", CultureInfo.InvariantCulture);
var difference = DateTime.Now - xdateValue;
if (difference.TotalMilliseconds < 200) ...

#3


1  

if (((DatetTime.Now - DateTime.ParseExact("03223311 ", "hhmmssff", CultureInfo.InvariantCulture))).Milliseconds > 200)
{

}