I was just wondering if my code contains defects or if there was a more efficient or general way to convert string to DateTime
object. In the input, I have a string in the UTC format.
public static DateTime ParseDateTime(string dateString)
{
DateTime dateTime;
if (!DateTime.TryParse(dateString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out dateTime))
{
if (!DateTime.TryParse(dateString, CultureInfo.CurrentCulture, DateTimeStyles.AssumeUniversal, out dateTime))
{
try
{
dateTime = DateTime.Parse(dateString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal);
}
catch (FormatException)
{
// Try to extract at least year from the string (the longest digits substring)
var yearMatch = Regex.Matches(dateString, @"\d{4}").Cast<Match>().FirstOrDefault();
if (yearMatch == null || string.IsNullOrWhiteSpace(yearMatch.Value))
{
throw;
}
// Only year really matters for Max and Min values of DateTime
var year = int.Parse(yearMatch.Value, CultureInfo.InvariantCulture);
// Try to determine what do we have (Min or Max value)
if (year == DateTime.MaxValue.Year)
{
dateTime = DateTime.MaxValue;
}
else
{
if (year == DateTime.MinValue.Year)
{
dateTime = DateTime.MinValue;
}
else
{
throw;
}
}
}
}
}
dateTime = dateTime.ToUniversalTime();
return dateTime;
}
dateString
which is beyond the scope of the method. Where does that string come from? How is it created? Many of these questions blend into @dcastro's answer. \$\endgroup\$