Reputation: 139
I'm trying to find the time duration between time range and convert it to hour, minutes and seconds. Hours should added should not get converted to 24 hour. if there is 50 hours 30 min and 30 seconds it should display as 50:30:30, If the minute duration exceeds 59 it should add to hours same in case of seconds.
Please see the complete code.Both methods are not giving the correct answer. Method GetSumOfDuration is considering 0.30 as 0.3 so its not giving the correct answer. method GetSumOfDurationFromSecond fails when there is more than 24 hours difference.
using System;
using System.Collections.Generic;
using System.Linq;
namespace TimeCalculationApp
{
public class ProcessDetail
{
public DateTime? StartTime { get; set; }
public DateTime? EndTime { get; set; }
public double? DurationInSeconds
{
get
{
if (StartTime != null && EndTime != null)
return (EndTime.Value - StartTime.Value).TotalSeconds;
return null;
}
}
public double? Duration
{
get
{
if (StartTime != null && EndTime != null)
return double.Parse(DateTimeHelper.GetTimeDuration(StartTime, EndTime));
return null;
}
}
}
class DateTimeHelper
{
public static string GetTimeDuration(DateTime? sDateTime, DateTime? eDateTime)
{
if (sDateTime != null && eDateTime != null)
{
if (sDateTime.Value <= eDateTime.Value)
{
var tsdiff = eDateTime.Value - sDateTime.Value;
var ts = TimeSpan.FromSeconds(tsdiff.TotalSeconds);
return string.Format("{0}.{1}", ts.Hours.ToString("0"), ts.Minutes.ToString("D2"));
}
return "0.00";
}
return "0.00";
}
public static string GetSumOfDuration(List<ProcessDetail> processDetails)
{
TimeSpan? sumDuration = null;
var totalhours = 0;
var totalminutes = 0;
foreach (var processDetail in processDetails)
{
if (processDetail.Duration != null)
{
var splitString = processDetail.Duration.ToString().Split('.');
var hour = splitString.Length > 0 ? splitString[0] : "0";
var minutes = splitString.Length > 1 ? splitString[1] : "0";
totalhours += int.Parse(hour);
totalminutes += int.Parse(minutes);
sumDuration = new TimeSpan(totalhours, totalminutes, 0);
}
}
return sumDuration == null
? null
: Math.Floor(sumDuration.Value.TotalHours).ToString("0") + ":" +
sumDuration.Value.Minutes.ToString("D2");
}
public static string GetSumOfDurationFromSecond(List<ProcessDetail> processDetails, bool includeSeconds = false)
{
var seconds = processDetails.Where(x => x.DurationInSeconds != null).Sum(x => x.DurationInSeconds);
if (seconds == null) return null;
var ts = TimeSpan.FromSeconds(seconds.Value);
return includeSeconds ? string.Format("{0}:{1}:{2}", ts.Hours.ToString("0"), ts.Minutes.ToString("D2"), ts.Seconds.ToString("D2")) :
string.Format("{0}:{1}", ts.Hours.ToString("0"), ts.Minutes.ToString("D2"));
}
}
class Program
{
static void Main(string[] args)
{
var processDetails = GetProcessDetails();
var duration = DateTimeHelper.GetSumOfDuration(processDetails);
var durationFromSeconds = DateTimeHelper.GetSumOfDurationFromSecond(processDetails);
Console.WriteLine(duration);
Console.WriteLine(durationFromSeconds);
processDetails = GetProcessDetailsTestData();
duration = DateTimeHelper.GetSumOfDuration(processDetails);
durationFromSeconds = DateTimeHelper.GetSumOfDurationFromSecond(processDetails);
Console.WriteLine(duration);
Console.WriteLine(durationFromSeconds);
Console.ReadKey();
}
private static List<ProcessDetail> GetProcessDetails()
{
return new List<ProcessDetail>
{
new ProcessDetail
{
StartTime = new DateTime(2017, 01, 01, 1, 0, 0),
EndTime = new DateTime(2017, 01, 01, 7, 59, 0)
},
new ProcessDetail
{
StartTime = new DateTime(2017, 01, 01, 1, 0, 0),
EndTime = new DateTime(2017, 01, 01, 17, 3, 45)
},
new ProcessDetail
{
StartTime = new DateTime(2017, 01, 01, 1, 0, 0),
EndTime = new DateTime(2017, 01, 01, 10, 0, 20)
},
new ProcessDetail
{
StartTime = new DateTime(2017, 01, 01, 1, 0, 0),
EndTime = new DateTime(2017, 01, 01, 15, 1, 12)
}
};
}
private static List<ProcessDetail> GetProcessDetailsTestData()
{
return new List<ProcessDetail>
{
new ProcessDetail
{
StartTime = DateTime.Parse("11/01/2017 06:36:28"),
EndTime = DateTime.Parse("11/01/2017 06:53:51")
},
new ProcessDetail
{
StartTime = DateTime.Parse("11/01/2017 09:12:46"),
EndTime = DateTime.Parse("11/01/2017 09:43:00")
},
new ProcessDetail
{
StartTime =DateTime.Parse("11/01/2017 15:29:25"),
EndTime = DateTime.Parse("11/01/2017 15:37:26")
},
new ProcessDetail
{
StartTime = DateTime.Parse("11/01/2017 15:19:19"),
EndTime = DateTime.Parse("11/01/2017 15:27:52")
},
new ProcessDetail
{
StartTime = DateTime.Parse("12/01/2017 01:05:43"),
EndTime = DateTime.Parse("12/01/2017 01:08:37")
}
};
}
}
}
Upvotes: 0
Views: 6013
Reputation: 81
I agree with Thomas Voß that you should use Timespan. However TotalHours should be casted to int to get proper number of hours.
string result = (int)elapsedTime.TotalHours + ":" + elapsedTime.Minutes + ":" + elapsedTime.Seconds
If you can consider displaying the result in days format you could utilize TimeSpan Formatting :
elapsedTime.ToString("dd\.hh\:mm\:ss")
You can read more about custom TimeSpan Formatting here
Upvotes: 0
Reputation: 9469
This should give the total hours between the dates.
DateTime dt1 = new DateTime(2016, 1, 1);
DateTime dt2 = new DateTime(2016, 1, 5);
TimeSpan difference = dt2 - dt1;
int totalDaysToHours = difference.Days * 24;
Console.WriteLine((difference.Hours + totalDaysToHours) + " hours " + difference.Minutes + " Minutes " + difference.Seconds + " seconds" );
Console.ReadKey();
Upvotes: 2
Reputation: 1165
You can just substract the starttime from the endtime. The result will be a Timespan object.
// Set startime example to one hour ten minutes and 30 seconds ago
DateTime startTime = DateTime.Now.AddSeconds(-4230);
DateTime endTime = DateTime.Now;
TimeSpan elapsedTime = endTime-startTime;
// Print out the elapsed time in hour:minutes:seconds to string
string result = elapsedTime.TotalHours + ":" + elapsedTime.Minutes + ":" + elapsedTime.Seconds
Be aware that TimeSpan provides Properties for e.g Hours and TotalHours. Hours can have a value between 0-23 (when the value would exceed 23 the property Days is increased instead) whereas TotalHours provides the total number of full hours
Upvotes: 0
Reputation: 46
You can fix a time span of the difference by subtract actions.
TimeSpan time1 = TimeSpan.Parse(date1);
TimeSpan time2 = TimeSpan.Parse(date2);
TimeSpan difference = time1 - time2;
int hours = difference.Hours;
int minutes = difference.Minutes;
Upvotes: 0