String is not a valid datetime

I am not able to convert string to datetime i am trying to calculate timeused

public int gettimeused(string start, string stop)
        {
            int value = 0;
            try
            {
                DateTime starttime = DateTime.Parse(start);
                DateTime stoptime = DateTime.Parse(stop);
                
                //IF['Stop Time'>='Start Time',('Stop Time'-'Start Time')*24*60,(24*60-'Start Time'*24*60)+('Stop Time'*24*60)] <- what i am trying to accomplish
                if (Convert.ToDateTime(stop) >= Convert.ToDateTime(start))
                {
                    int diff = (stoptime.Minute - starttime.Minute);
                    value = Convert.ToInt16(diff) * 24;
                }
                else
                {
                    value = 24 * 60 - (Convert.ToInt16(start) * 24) + Convert.ToInt16(stop) * 24;
                }
               
            }
            catch(Exception ex)
            {
                lblErrorMessage.Text = ex.Message.ToString();
            }
            return value;
        }

Open in new window


start value = "12:00" stop value = "24:00"

the error i am getting string is not recognized as a valid datetime
Aravind RanganathanWindows Application DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

AndyAinscowFreelance programmer / ConsultantCommented:
>>start value = "12:00" stop value = "24:00"

Neither of those is a DateTime - hence your error.  Assuming that is always the format then you might want to split the string and process the parts.
Something like this to get the start hours and minutes.  (Same procedure for the end)
string[] s = start.Split(":");
int hoursStart = Convert.ToInt(s[0]);
int minsStart = Convert.ToInt(s[1]);
0
Aravind RanganathanWindows Application DeveloperAuthor Commented:
@AndyAinsow How do i check this condition IF['Stop Time'>='Start Time' if its split up by hours and minutes?
0
Chris StanyonWebDevCommented:
The problem you have is not with the StartTime of 12:00 - it's with the StopTime of 24:00 - there is no such time as 24:00 - midnight is represented as 00:00, so you will need some logic to handle that. Probably the simplest way is to do a quick check for "24:00". If that's the value, change it to 00:00, parse the date and add a day.

DateTime startDate = DateTime.Parse(start);
DateTime stopDate = (stop == "24:00") ? stopDate = DateTime.Parse("00:00").AddDays(1) : DateTime.Parse(stop);

if (stopDate >= startDate)
    ...

Open in new window

0
OWASP: Forgery and Phishing

Learn the techniques to avoid forgery and phishing attacks and the types of attacks an application or network may face.

Chris StanyonWebDevCommented:
Once you've got the StartTime and EndTime, if you're just after the difference in minutes, then just use a TimeSpan:

TimeSpan span = stopDate - startDate;
Double totalMinutes = span.TotalMinutes;

Open in new window

0
AndyAinscowFreelance programmer / ConsultantCommented:
Hours*60 gives minutes.  
So 12 hours 40 minutes is 12*60+40 minutes.  Likewise 18 hours 10 minutes is 18*60+10 minutes.  Time difference is 18*60+10 - 12*60+40 minutes
0
Gustav BrockCIOCommented:
Have in mind, that your hours should result in a timespan. Thus, you may have to follow a straight and simpler, though slightly longer, route to avoid traps, and to have code easy to maintain.

So, first find the timespans of your entered strings, then subtract these, and finally convert the net timespan to minutes.

string start = "12:10";
string stop = "24:15";

TimeSpan startHours = TimeSpan.FromHours(Convert.ToDouble(start.Split(':')[0]));
TimeSpan startMinutes = TimeSpan.FromMinutes(Convert.ToDouble(start.Split(':')[1]));
TimeSpan startTime = startHours.Add(startMinutes);

TimeSpan stopHours = TimeSpan.FromHours(Convert.ToDouble(stop.Split(':')[0]));
TimeSpan stopMinutes = TimeSpan.FromMinutes(Convert.ToDouble(stop.Split(':')[1]));
TimeSpan stopTime = stopHours.Add(stopMinutes);

TimeSpan timeUsed = stopTime.Subtract(startTime);

int usedMinutes = (int)timeUsed.TotalMinutes;

// usedMinutes -> 725

Open in new window

Of course, proper error handling - indeed validation of the string inputs - must be added.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
it_saigeDeveloperCommented:
Another alternative, is to use ParseExact or TryParseExact and specify the format(s) of the strings; e.g. -
using System;
using System.Globalization;

namespace EE_Q29097050
{
	class Program
	{
		static void Main(string[] args)
		{
			Console.WriteLine($"Time used in minutes: {GetTimeUsed("12:00", "00:00")}");
			Console.ReadLine();
		}

		static double GetTimeUsed(string start, string stop)
		{
			DateTime startTime, stopTime;
			TimeSpan result;
			var formats = new[] { "H:m", "H:m", "HH:m", "HH:mm" };
			try
			{
				DateTime.TryParseExact(start, formats, CultureInfo.CurrentCulture, DateTimeStyles.None, out startTime);
				DateTime.TryParseExact(stop, formats, CultureInfo.CurrentCulture, DateTimeStyles.None, out stopTime);
				result = startTime - stopTime;
			}
			catch (Exception)
			{
				result = new TimeSpan();
			}
			return result.TotalMinutes;
		}
	}
}

Open in new window

Which produces the following output -Capture.PNG-saige-
0
Aravind RanganathanWindows Application DeveloperAuthor Commented:
Thnaks For All the help guys
0
Gustav BrockCIOCommented:
You are welcome!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.