2

I'm trying to get the time elapsed from a starting date to an end date in C#

Assuming that my start date is "11/19/2017 05:50 P.M." and the end date is "11/19/2017 05:55 P.M." get the time elapsed, in this case was 5:00 minutes.

But also would like to get for example "5 days and 25 minutes" elapsed

any idea to do this?

  • 4
    TimeSpan duration = endDate - startDate – Sir Rufo Nov 20 '17 at 01:01
  • i checked the answer and worked for me, if you want to delete this post is ok. – Jorge Morales Nov 20 '17 at 01:18
  • You might also consider that "5 days and 25 minutes" is approximately "5 days". That's the concept for ["time ago"](https://stackoverflow.com/questions/11/calculate-relative-time-in-c-sharp) libraries. But if you do want precise concepts, [Noda Time](https://nodatime.org/) is the thing to use. Where I'm from, some days have 23 hours, some 24, some 25. – Tom Blodget Nov 20 '17 at 01:20
  • 1
    @Jorge If it worked for you, you should upvote it and set it as the accepted answer. – ProgrammingLlama Nov 20 '17 at 01:44

2 Answers2

3
TimeSpan span = (EndDateTime - StartDateTime);

String.Format("{0} days, {1} hours, {2} minutes, {3} seconds", 
    span.Days, span.Hours, span.Minutes, span.Seconds);
TanvirArjel
  • 30,049
  • 14
  • 78
  • 114
0

Do this. Just subtract the dates and call the method you want

 DateTime Date1=new DateTime(2017, 11, 29, 5 + 12, 50, 0);
 DateTime date2 = new DateTime(2017, 11, 29, 5 + 12, 55, 0);
 var diff = (date2 - date1);

Then call the method you want from the resulting diff object;

double minutesDiff=diff.TotalMinutes;
int days=minutesDiff \(24*60);
int minLeft=  minutesDiff %(24*60);

You can finish it from here

Lolu Omosewo
  • 263
  • 1
  • 4