0

I have the following inside my asp.net mvc web application:-

 scan.StartDate = System.DateTime.Now;
//do long job....
 scan.EndDate = System.DateTime.Now;

    var duration = (scan.EndDate - scan.StartDate);

now the duration will be something such as 00:00:50.0250000 so my question is how i can truncate the miliseconds and show only hour:minute:seconds ?

John John
  • 1
  • 72
  • 238
  • 501
  • In a string? https://msdn.microsoft.com/en-us/library/1ecy8h51(v=vs.110).aspx – TyCobb Sep 01 '15 at 23:00
  • yes i am converting it to a string later on , to send in an email – John John Sep 01 '15 at 23:01
  • Then the link supplied is what you want. It shows how to format the TimeSpan. – TyCobb Sep 01 '15 at 23:02
  • [Duplicate](http://stackoverflow.com/questions/1004698/how-to-truncate-milliseconds-off-of-a-net-datetime) shows what your are asking, if you need *just formatting* - answers to this post give you a way. – Alexei Levenkov Sep 01 '15 at 23:25
  • I would prefer the Stopwatch class. Your method may occasionally give an inaccurate result, e.g. if daylight savings time starts/ends or the time is adjusted by the Windows Time Service while your long job is running: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.stopwatch?view=net-7.0 – Joe Mar 31 '23 at 12:21

2 Answers2

2

Here is the code which shall remove the milliseconds.msdn.

DateTime StartDate = System.DateTime.Now;
//do long job....
DateTime EndDate = System.DateTime.Now;               
var duration = (EndDate - StartDate);     
string st=duration.ToString("hh\\:mm\\:ss");              
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
sumeet kumar
  • 2,628
  • 1
  • 16
  • 24
1

Use this:

var result = string.Format("{0:D2}:{1:D2}:{2:D2}", duration.Hours, duration.Minutes, duration.Seconds);
Yacoub Massad
  • 27,509
  • 2
  • 36
  • 62