Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format Diffrence time between two DateTime objects

Tags:

c#

.net

datetime

I've got a two DateTime objects - StartDate and EndDate I would like format difference between two dates like HH:mm:ss.

EndTime.Subtract(StartDate).Hours + ":" +
EndTime.Subtract(StartDate).Minutes + ":" +
EndTime.Subtract(StartDate).Seconds

This works fine but looks ugly, I tried like this:

EndTime.Subtract(StartDate).ToString("HH:mm:ss")

but this threw Exception:

Input string was not in a correct format

What I'm doing wrong? I Would like have format like this - 01:55:23

like image 273
user3468055 Avatar asked Feb 10 '26 19:02

user3468055


1 Answers

try this.

EndTime.Subtract(StartDate).ToString("hh\\:mm\\:ss");

Acccording to MSDN: https://msdn.microsoft.com/en-us/library/ee372287(v=vs.110).aspx

The custom TimeSpan format specifiers do not include placeholder separator symbols, such as the symbols that separate days from hours, hours from minutes, or seconds from fractional seconds. Instead, these symbols must be included in the custom format string as string literals. For example, "dd.hh:mm" defines a period (.) as the separator between days and hours, and a colon (:) as the separator between hours and minutes.

Therefore, to use ':' as the separator, you must include '\' before it.

like image 147
Mango Wong Avatar answered Feb 12 '26 16:02

Mango Wong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!