Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Calculate how long it will be until specified timespan

So I am trying to calculate how long it will be until a specific time. ButI cant seem to get it working.

An example is say im trying to calculate how long it will be from now to 06:00:00am So say it is 10:30pm I want to see how long it will be until til 6am the next day. So the correct answer would be 7 hours and 30 mins. Or another example say it is 8:30pm I want to see how long it will be until 10pm. If anyone could provide me with some code to help it would be greatly appreciated!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Compare the timespan first then add one day if needed.

        static TimeSpan TimeDiff(TimeSpan nowSpan, TimeSpan ts)
        {
            if (nowSpan > ts)
            {
                ts = ts.Add(TimeSpan.FromDays(1));
            }
            return ts - nowSpan;
        }

        static void Main(string[] args)
        {
            Console.WriteLine(TimeDiff(new TimeSpan(22, 30, 0), new TimeSpan(6, 0, 0)));
            //  07:30:00
            Console.WriteLine(TimeDiff(new TimeSpan(20, 30, 0), new TimeSpan(22, 0, 0)));
            //  01:30:00
            // You may want use DateTime.Now.TimeOfDay as the first parameter
            Console.ReadKey();
        }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading