• Status: Solved
  • Priority: High
  • Security: Public
  • Views: 55
  • Last Modified:

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
0
Aravind Ranganathan
Asked:
Aravind Ranganathan
  • 2
  • 2
  • 2
  • +2
2 Solutions
 
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 StanyonCommented:
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
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
Chris StanyonCommented:
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
 
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

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