How do I subtract time in c#.net?

How do I subtract time  in c#.net?

How do I subtract for example (7:40 pm  - 7:20 pm) to result in just minutes.

My times are represented in this exact format
wademiAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
RishadanPortConnect With a Mentor Commented:
Here is my full updated solution:
DateTime time = Convert.ToDateTime("7:40pm");
DateTime time2 = Convert.ToDateTime("7:20pm");
 
TimeSpan span = new TimeSpan(time.Hour, time.Minute, time.Second);
TimeSpan span2 = new TimeSpan(time2.Hour, time2.Minute, time2.Second);
 
MessageBox.Show("Total Minutes is " 
   + span.TotalMinutes - span2.TotalMinutes);

Open in new window

0
 
RishadanPortCommented:
Convert both times into second format...

Then subtract seconds, and convert seconds into minutes.

Use this:

            TimeSpan time = <some time>;
            TimeSpan time2 = ....;
            int totalSeconds = time2.TotalSeconds - time.TotalSeconds;
0
 
RishadanPortCommented:
Further example listed below.

You may need to research a bit more on how to convert to a DateTime from a string
DateTime time = Convert.ToDateTime(<put time here>);
DateTime time2 = Convert.ToDateTime(<put time here>);
 
TimeSpan stime = new TimeSpan(time.Hour, time.Minute, time.Second);
TimeSpan stime2 = new TimeSpan(time2.Hour, time2.Minute, time2.Second);
 
int seconds = stime2.TotalSeconds - stime.TotalSeconds;
int minutes = seconds * 60;

Open in new window

0
 
RishadanPortCommented:
It turns out that this compiles, and runs correctly:

DateTime time = Convert.ToDateTime("7:40 pm");
DateTime time2 = Convert.ToDateTime("7:20 pm");
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.