I am trying to parse a nullable datetime which contains a date and a string which is the time. I would like to be able to put the datetime and the time string together to parse a datetime. But the time and date could be in a inconsistent format. Here is what I have come up with but it breaks for certain formats:
private DateTime? ParseToDateTime(DateTime? dateTime, string time)
{
if (dateTime.HasValue)
{
//Parse the time
time = TimeToParse(time);
if (TimeValid(time))
{
var inptTime = time.PadLeft(4, '0');
var hrs = int.Parse(inptTime.Left(2));
var mins = int.Parse(inptTime.Right(2)) + hrs * 60;
return DateTime.SpecifyKind(dateTime.Value.Date.Add(TimeSpan.FromMinutes(mins)), DateTimeKind.Local);
}
}
return null;
}
private string TimeToParse(string time)
{
if (time.Contains("+"))
{
time = time.Substring(0, time.IndexOf("+", StringComparison.Ordinal));
}
return time;
}
private static bool TimeValid(string time)
{
if (string.IsNullOrEmpty(time)) return false;
if (time.Length < 4) return false;
if (time.Length > 4) return false;
return true;
}
I looked into tryparse exact also but the format could be different and we are talking two different values here any idea?