在C#中获取时间差的时间差 [英] To take time difference in timespan in C#
问题描述
Iam开发计时器应用程序,我已经创建了计时器,并希望在HH:MM:SS两个时间的差异,从我这边,秒解决方案工作完美,但我无法正确得到分钟。
例如:time1:18:41:46
time2:18:42:12
当timer2- timer1
我的输出应该是0:01:26
但我的输出为00:00:26。请好好纠正我的问题
Iam developing timer application, where i have created timer and want to make difference of both time in HH:MM:SS,from my side, seconds solution works perfect, but i couldn't get minutes correctly.
for example: time1: 18:41:46
time2: 18:42:12
when timer2- timer1
my output should be 0:01:26
but iam getting output as 00:00:26 . kindly rectify my problem
try
{
List<string> distinct = list.Distinct().ToList();
foreach (string value in distinct)
{
string svalue = value.Split(';')[1];
if (svalue == "SessionUnlock")
{
unlockvalue = value.Split(';')[0];
dt1 = DateTime.ParseExact(unlockvalue, "HH:mm:ss", new DateTimeFormatInfo());
}
else
{
lockvalue = value.Split(';')[0];
dt2 = DateTime.ParseExact(lockvalue, "HH:mm:ss", new DateTimeFormatInfo());
TimeSpan ts = dt2.Subtract(dt1);
MessageBox.Show(ts.ToString());
}
}
Inside Distict list i have一个列表如
[0] = 18:37:20; SessionUnlock
[1] = 18:37:54; SessionLock
[2] = 18:41:46; SessionUnlock
[3] = 18:42:12; SessionLock
我尝试过:
Inside Distict list i have a list such as
[0]=18:37:20;SessionUnlock
[1]=18:37:54;SessionLock
[2]=18:41:46;SessionUnlock
[3]=18:42:12;SessionLock
What I have tried:
try
{
List<string> distinct = list.Distinct().ToList();
foreach (string value in distinct)
{
string svalue = value.Split(';')[1];
if (svalue == "SessionUnlock")
{
unlockvalue = value.Split(';')[0];
dt1 = DateTime.ParseExact(unlockvalue, "HH:mm:ss", new DateTimeFormatInfo());
}
else
{
lockvalue = value.Split(';')[0];
dt2 = DateTime.ParseExact(lockvalue, "HH:mm:ss", new DateTimeFormatInfo());
TimeSpan ts = dt2.Subtract(dt1);
MessageBox.Show(ts.ToString());
}
}
推荐答案
那是因为结果是26秒,不是一分钟和26秒:
That's because the result is 26 seconds, not one minute and 26 seconds:
18:42:12 - 18:41:46 == 26 seconds
18:37:54 - 18:37:20 == 34 seconds
例如: time1:18:41:46
time2:18:42:12
当timer2- timer1
我的输出应为0:01: 26
for example: time1: 18:41:46
time2: 18:42:12
when timer2- timer1
my output should be 0:01:26
这些时间之间有26秒,输出正确。添加14秒到18:41:46到18:42:00,然后另外12到18:42:21。 14 + 12 = 26。
There are 26 seconds between those times, your output is correct. Add 14 seconds to 18:41:46 to get to 18:42:00, then another 12 gets you to 18:42:21. 14 + 12 = 26.
有时通过将其分解为简单测试更容易看到问题。这是我使用的一个:
Sometimes it is easier to see the problem by breaking it out into a simple test. Here is one that I used:
DateTime dt1 = DateTime.Now;
DateTime dt2 = dt1 + new TimeSpan(1, 23, 46);
TimeSpan ts = dt2 - dt1;
Console.WriteLine(ts); // outputs: 01:23:46
希望这有助于......
Hope this helps...
这篇关于在C#中获取时间差的时间差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!