Home > Enterprise >  is there any solution to find the time span between two time duration
is there any solution to find the time span between two time duration

Time:01-20

I have two time like 100:45 and 395:50 I need to find the subtraction and addition between these two times in asp.net web application

I will expect like this 100:45 395:50=496:35 and 100:45-395:50=295:05

CodePudding user response:

assuming the times are given in a string. then you can split the times to get the equivalent minutes. now it becomes a simple mathematics problem and now perform addition and subtraction accordingly.

string time = "100:45";
string[] parts = time.Split(':');
int hours = int.Parse(parts[0]);
int minutes = int.Parse(parts[1]);
int totalMinutes = hours * 60   minutes;

so for your case

int mins1 = 100 * 60   45;
int mins2 = 395 * 60   50;
int totalMinutes = mins1   mins2;
int totalHours = totalMinutes / 60;
int remainingMinutes = totalMinutes % 60;
string sum = $"{totalHours}:{remainingMinutes}";

use the same concept to get the subtraction as well.

CodePudding user response:

You can convert times to TimeSpan.FromMinutes and to get the desired output using TimeSpan.TotalHours and TimeSpan.Minutes

string s1 = "100:45";
string s2 = "395:50";

TimeSpan spWorkMin = TimeSpan.FromMinutes(int.Parse(s1.Split(':')[0]) * 60   
                                          int.Parse(s2.Split(':')[0]) * 60  
                                          int.Parse(s1.Split(':')[1])   
                                          int.Parse(s2.Split(':')[1]));
var sum =string.Format("{0:00}:{1:00}", (int)tSum.TotalHours, tSum.Minutes);//496:35

TimeSpan tsub = TimeSpan.FromMinutes(int.Parse(s1.Split(':')[0]) * 60 - 
                                     int.Parse(s2.Split(':')[0]) * 60  
                                     int.Parse(s1.Split(':')[1]) - 
                                     int.Parse(s2.Split(':')[1]));
var subtract = string.Format("{0:00}:{1:00}", Math.Abs((int)tsub.TotalHours),Math.Abs(tsub.Minutes)); //295:05

CodePudding user response:

TimeSpan do the trick

        TimeSpan ts1 = new TimeSpan(0, 100, 45);
        TimeSpan ts2 = new TimeSpan(0, 395, 50);

        var tsResult = ts1   ts2;
        string outPut = string.Format("{0}:{1}", Math.Floor(tsResult.TotalMinutes), tsResult.Seconds);
  • Related