I have two dates, one less than the other. I want to create a string such as this one
\"0 days, 0 hours, 23 minutes, 18 seconds\"
representing the differenc
Use a TimeSpan
DateTime startTime = DateTime.Now;
DateTime endTime = DateTime.Now.AddSeconds( 75 );
TimeSpan span = endTime.Subtract ( startTime );
Console.WriteLine( "Time Difference (seconds): " + span.Seconds );
Console.WriteLine( "Time Difference (minutes): " + span.Minutes );
Console.WriteLine( "Time Difference (hours): " + span.Hours );
Console.WriteLine( "Time Difference (days): " + span.Days );
String yourString = string.Format("{0} days, {1} hours, {2} minues, {3} seconds",
span.Days, span.Hours, span.Minutes, span.Seconds);
Use the TimeSpan class, which you'll get when you subtract the dates.
You can format the output using standard or custom format strings.
"0 days, 0 hours, 23 minutes, 18 seconds"
can be had with something like:
TimeSpan ts = DateTime.Now - DateTime.Today;
Console.WriteLine(
string.Format("{0:%d} days, {0:%h} hours, {0:%m} minutes, {0:%s} seconds", ts)
);
IMO, it's cleaner and easier to use string.Format
instead of having to escape the words in your format string (which you'd need if you just used .ToString
) or building it up manually.
TimeSpan is the object you need:
TimeSpan span = (DateTime.Now - DateTime.Now);
String.Format("{0} days, {1} hours, {2} minutes, {3} seconds",
span.Days, span.Hours, span.Minutes, span.Seconds);