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 difference between the two dates. How can I get these elements of this string?
The answer is exactly eight hours. If you leave your kids early at school and pick them up in the afternoon, you might wonder how much time they spend in school each day. If you leave them at 7AM and pick them up at 3PM then the question is how many hours is 7AM to 3PM and the answer is eight hours (15-7 = 8).
Most of the work in this formula is done by the TEXT function, which applies a custom number format for hours and minutes to a value created by subtracting the start date from the end date.
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);
When you subtract one DateTime
from another, you get a TimeSpan
instance, which exposes those values.
TimeSpan diff = DateTime.Now - DateTime.Today; string formatted = string.Format( CultureInfo.CurrentCulture, "{0} days, {1} hours, {2} minutes, {3} seconds", diff.Days, diff.Hours, diff.Minutes, diff.Seconds);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With