[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1658
  • Last Modified:

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
0
wademi
Asked:
wademi
  • 4
1 Solution
 
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
 
RishadanPortCommented:
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

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now