在C#中添加小时和分钟的差异

时间:2018-07-05 14:28:37

标签: c# date datetime-format

您好,我必须使用以下格式的时差总和:

  1. StartEnd [0]:08:50
  2. StartEnd 1:10:30
  3. StartEnd [2]:12:30
  4. StartEnd [3]:15:30

    结果 =(StartEnd 1 -StartEnd [0])+(StartEnd [3] -StartEnd [2])

如何获取HH:mm格式的结果值?

C#代码:

String[] HourAndMinute = new String[100];
foreach (DataRow dr in dt.Rows)
{
    HourAndMinute[conta] = dr["StartEnd"].ToString();
    conta++;
}
conta++;
int n = 0;
for (int i = 0; i < conta / 2; i++)
{

    TimeSpan tempoUscita = TimeSpan.Parse(HourAndMinute[i]);
    TimeSpan tempoIngresso = TimeSpan.Parse(HourAndMinute[i + 1]);
    totalSum = totalSum + (tempoUscita - tempoIngresso);
    n++;
}

Totale = "" + totalSum.Hours.ToString().Replace("-", "").ToString() + ":" + totalSum.Minutes.ToString().Replace("-","").ToString();

SQL查询:

select FORMAT(DataCreazione,'HH:mm') as StartEnd
from Marcatura
where  (Stato='Enter' or Stato='Exit') 

表Sql映像:

enter image description here

2 个答案:

答案 0 :(得分:4)

TimeSpan totalSum = TimeSpan.Zero;
foreach (DataRow dr in dt.Rows)
{
    string[] HourAndMinute = dr["StartEnd"].ToString().Split(); //This String contains 08:50 10:30 ...
    TimeSpan tsStart = TimeSpan.Parse(HourAndMinute[0].Trim());
    TimeSpan tsEnd = TimeSpan.Parse(HourAndMinute[1].Trim());
    totalSum += tsEnd - tsStart;
}

好吧,现在您已经完全更改了问题,第一个StartEnd08:50 10:30,现在每个记录都包含08:5010:30。那个数据模型看起来不好,但是...

TimeSpan totalSum = TimeSpan.Zero;
List<TimeSpan> orderedTimespans = dt.AsEnumerable()
    .Select(r => TimeSpan.Parse(r.Field<string>("StartEnd")))
    .OrderBy(ts => ts)
    .ToList();

for (int index = 0; index < orderedTimespans.Count; index+=2)
{
    TimeSpan tsStart = orderedTimespans[index];
    TimeSpan tsEnd = orderedTimespans[index + 1];
    totalSum += tsEnd - tsStart;
}

答案 1 :(得分:1)

当您将时间条目记录为 DateTime 时,请按原样读取这些 (无字符串,无格式)并将其转换为 TimeSpan

DateTime[] startEnd = new DateTime[4];

// Read data from table. 
// For demonstration, array is here filled manually with your values:
startEnd[0] = DateTime.Today.AddHours(8).AddMinutes(50);
startEnd[1] = DateTime.Today.AddHours(10).AddMinutes(30);
startEnd[2] = DateTime.Today.AddHours(12).AddMinutes(30);
startEnd[3] = DateTime.Today.AddHours(15).AddMinutes(30);

TimeSpan totalTime = new TimeSpan(0);

// Add/subtract the timespans in pairs.
for (int i = 0; i < 4 ; i += 2)
{
    totalTime += startEnd[i + 1].Subtract(startEnd[i]);
}

// Display totalTime as formatted text.
Console.WriteLine(totalTime.ToString("hh':'mm"));