C# Get DateTime from input

Date: 2019-11-18
public static DateTime? GetDateTimeFromInput(string dateTimeStr) {
	if (string.IsNullOrWhiteSpace(dateTimeStr))
		return null;
	if (DateTime.TryParse(dateTimeStr, out var dateTime)) 
		return dateTime;
	return null;
}
public static bool GetBoolFromInput(string input, bool def = false)
{
	if (string.IsNullOrWhiteSpace(input))
		return def;
	if (bool.TryParse(input.Trim(), out var res))
		return res;
	return def;
}
public static IEnumerable<int> GetNumberMatches(string s) => Regex.Matches(s, @"\d+").Select(m => int.TryParse(m.Value, out var i) ? i : 0);

public static DateTime? GetDateFromNumbers(string s) {
    var numbers = GetNumberMatches(s).ToList();
    if (numbers.Count < 3) return null;
    var y = numbers.ElementAtOrDefault(0);
    var m = numbers.ElementAtOrDefault(1);
    var d = numbers.ElementAtOrDefault(2);
    if (y == 0 || m == 0 || d == 0) return null;
    var h = numbers.ElementAtOrDefault(3);
    var min = numbers.ElementAtOrDefault(4);
    var sec = numbers.ElementAtOrDefault(5);
    return new DateTime(y,m,d,h,min,sec);
}

public static DateTime? DateFromString(string? s)
{
    if (s == null) return null;
    if (DateTime.TryParse(s, out var d)) return  d;
    return GetDateFromNumbers(s);
}
28860cookie-checkC# Get DateTime from input