Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

How to calculate the difference between two time periods in C#

1 Answer

0 votes
using System;

public class TimeDiff
{
	int seconds;
	int minutes;
	int hours;

	public TimeDiff(int hours, int minutes, int seconds) {
		this.hours = hours;
		this.minutes = minutes;
		this.seconds = seconds;
	}

	public static TimeDiff timeDifference(TimeDiff start, TimeDiff end) {
		TimeDiff timediff = new TimeDiff(0, 0, 0);

		if (start.seconds > end.seconds) {
			end.minutes--;
			end.seconds += 60;
		}

		timediff.seconds = end.seconds - start.seconds;

		if (start.minutes > end.minutes) {
			end.hours--;
			end.minutes += 60;
		}

		timediff.minutes = end.minutes - start.minutes;
		timediff.hours = end.hours - start.hours;

		return timediff;
	}

	public static void Main(string[] args)
	{
		TimeDiff start = new TimeDiff(7, 11, 25);
		TimeDiff end = new TimeDiff(11, 32, 17);

		TimeDiff timediff = timeDifference(start, end);

		Console.Write("{0:D}:{1:D}:{2:D} - ", start.hours, start.minutes, start.seconds);
		Console.Write("{0:D}:{1:D}:{2:D} ", end.hours, end.minutes, end.seconds);
		Console.Write("= {0:D}:{1:D}:{2:D}", timediff.hours, timediff.minutes, timediff.seconds);
	}
}




/*
run:
 
7:11:25 - 11:31:77 = 4:20:52
 
*/

 



answered Sep 15, 2022 by avibootz

Related questions

1 answer 126 views
1 answer 120 views
1 answer 129 views
1 answer 134 views
2 answers 207 views
...