What is the best way to convert seconds into (Hour:Minutes:Seconds:Milliseconds) time?
Let's say I have 80 seconds, are there any specialized classes/techniques in .NET that would allow me to convert those 80 seconds into (00h:00m:00s:00ms) format like to DateTime or something?
If you know you have a number of seconds, you can create a TimeSpan value by calling TimeSpan.FromSeconds:
You can then obtain the number of days, hours, minutes, or seconds. Or use one of the ToString overloads to output it in whatever manner you like.
For .NET < 4.0 (e.x: Unity) you can write an extension method to have the
TimeSpan.ToString(string format)
behavior like .NET > 4.0And from anywhere in your code you can use it like:
This way you can format any
TimeSpan
object by simply calling ToString from anywhere of your code.Why do people need TimeSpan AND DateTime if we have DateTime.AddSeconds()?
The date is arbitrary. totalSeconds can be greater than 59 and it is a double. Then you can format your time as you want using DateTime.ToString():
This does not work if totalSeconds < 0 or > 59:
//Test
For .Net <= 4.0 Use the TimeSpan class.
(As noted by Inder Kumar Rathore) For .NET > 4.0 you can use
(From Nick Molyneux) Ensure that seconds is less than
TimeSpan.MaxValue.TotalSeconds
to avoid an exception.I did some benchmarks to see what's the fastest way and these are my results and conclusions. I ran each method 10M times and added a comment with the average time per run.
If your input milliseconds are not limited to one day (your result may be 143:59:59.999), these are the options, from faster to slower:
If your input milliseconds are limited to one day (your result will never be greater then 23:59:59.999), these are the options, from faster to slower:
In case your input is just seconds, the methods are slightly faster. Again, if your input seconds are not limited to one day (your result may be 143:59:59):
And if your input seconds are limited to one day (your result will never be greater then 23:59:59):
As a final comment, let me add that I noticed that
string.Format
is a bit faster if you useD2
instead of00
.