How to Convert string “07:35” (HH:MM) to TimeSpan

While correct that this will work: TimeSpan time = TimeSpan.Parse(“07:35”); And if you are using it for validation… TimeSpan time; if (!TimeSpan.TryParse(“07:35”, out time)) { // handle validation error } Consider that TimeSpan is primarily intended to work with elapsed time, rather than time-of-day. It will accept values larger than 24 hours, and will accept … Read more

How to produce “human readable” strings to represent a TimeSpan

To get rid of the complex if and switch constructs you can use a Dictionary lookup for the correct format string based on TotalSeconds and a CustomFormatter to format the supplied Timespan accordingly. public string GetReadableTimespan(TimeSpan ts) { // formats and its cutoffs based on totalseconds var cutoff = new SortedList<long, string> { {59, “{3:S}” … Read more

Work with a time span in Javascript

Sounds like you need moment.js e.g. moment().subtract(‘days’, 6).calendar(); => last Sunday at 8:23 PM moment().startOf(‘hour’).fromNow(); => 26 minutes ago Edit: Pure JS date diff calculation: var date1 = new Date(“7/Nov/2012 20:30:00”); var date2 = new Date(“20/Nov/2012 19:15:00”); var diff = date2.getTime() – date1.getTime(); var days = Math.floor(diff / (1000 * 60 * 60 * 24)); … Read more

Getting time span between two times in C#?

string startTime = “7:00 AM”; string endTime = “2:00 PM”; TimeSpan duration = DateTime.Parse(endTime).Subtract(DateTime.Parse(startTime)); Console.WriteLine(duration); Console.ReadKey(); Will output: 07:00:00. It also works if the user input military time: string startTime = “7:00”; string endTime = “14:00″; TimeSpan duration = DateTime.Parse(endTime).Subtract(DateTime.Parse(startTime)); Console.WriteLine(duration); Console.ReadKey(); Outputs: 07:00:00. To change the format: duration.ToString(@”hh\:mm”) More info at: http://msdn.microsoft.com/en-us/library/ee372287.aspx Addendum: Over … Read more

Can you round a .NET TimeSpan object?

Sorry, guys, but both the question and the popular answer so far are wrong 🙂 The question is wrong because Tyndall asks for a way to round but shows an example of truncation. Will Dean’s answer is wrong because it also addresses truncation rather than rounding. (I suppose one could argue the answer is right … Read more

Sum of TimeSpans in C#

Unfortunately, there isn’t a an overload of Sum that accepts an IEnumerable<TimeSpan>. Additionally, there’s no current way of specifying operator-based generic constraints for type-parameters, so even though TimeSpan is “natively” summable, that fact can’t be picked up easily by generic code. One option would be to, as you say, sum up an integral-type equivalent to … Read more