Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Days, hours, minutes, seconds between two dates

Tags:

c#

.net

datetime

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?

like image 412
Sachin Kainth Avatar asked May 10 '12 16:05

Sachin Kainth


People also ask

How many hours is 730am to 330pm?

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).

How do I calculate the difference between two dates and hours in Excel?

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.


2 Answers

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); 
like image 122
Alexei Levenkov Avatar answered Oct 05 '22 00:10

Alexei Levenkov


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); 
like image 45
bdukes Avatar answered Oct 05 '22 00:10

bdukes