Created
April 29, 2024 14:31
-
-
Save martyncoup/9b371fe426b657ab92b38bdbdd3aa5b9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class Helper | |
{ | |
private static readonly string[] CUSTOM_DATE_FORMATS = new string[] | |
{ | |
"yyyyMMddTHHmmssZ", | |
"yyyyMMddTHHmmZ", | |
"yyyyMMddTHHmmss", | |
"yyyyMMddTHHmm", | |
"yyyyMMddHHmmss", | |
"yyyyMMddHHmm", | |
"yyyyMMdd", | |
"yyyy-MM-ddTHH-mm-ss", | |
"yyyy-MM-dd-HH-mm-ss", | |
"yyyy-MM-dd-HH-mm", | |
"yyyy-MM-dd", | |
"MM-dd-yyyy", | |
"dd/MM/yyyy" | |
}; | |
public static DateTime? ParseDateTime( | |
string dateToParse, | |
string[] formats = null, | |
IFormatProvider provider = null, | |
DateTimeStyles styles = DateTimeStyles.None) | |
{ | |
if (formats == null || !formats.Any()) | |
{ | |
formats = CUSTOM_DATE_FORMATS; | |
} | |
DateTime validDate; | |
foreach (var format in formats) | |
{ | |
if (format.EndsWith("Z")) | |
{ | |
if (DateTime.TryParseExact(dateToParse, format, provider, DateTimeStyles.AssumeUniversal, out validDate)) | |
{ | |
return validDate; | |
} | |
} | |
if (DateTime.TryParseExact(dateToParse, format, provider, styles, out validDate)) | |
{ | |
return validDate; | |
} | |
} | |
return null; | |
} | |
public static bool IsNullableType(Type type) | |
{ | |
return type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment