Say, I have two strings containing date/time in arbitrary user-provided format for an arbitrary culture:
string str1 = "6/19/2013";
string str2 = "6/19/2013 1 am";
I can parse them by doing:
DateTime dt1 = DateTime.Parse(str1);
DateTime dt2 = DateTime.Parse(str2);
But how do I know if the time part was present & parsed into the DateTime object?
What do you guys think about something like this?
public static DateTime ParseDateTimeWithTimeDifferentiation(string str, out bool bOutTimePresent)
{
//Parse date/time from 'str'
//'bOutTimePresent' = receives 'true' if time part was present
DateTime dtRes;
//Get formats for the current culture
DateTimeFormatInfo dtfi = CultureInfo.CurrentUICulture.DateTimeFormat;
DateTimeStyles dts = DateTimeStyles.AllowWhiteSpaces |
DateTimeStyles.AssumeLocal;
//Get all formats
string[] arrFmts = dtfi.GetAllDateTimePatterns();
foreach (string strFmt in arrFmts)
{
if (DateTime.TryParseExact(str, strFmt, CultureInfo.InvariantCulture, dts, out dtRes))
{
//Parsed it!
//These format codes come from here:
// http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
bOutTimePresent = strFmt.IndexOfAny(new char[] { 'H', 'h', 'm', 's', 'f', 'F', 't', 'z' }) != -1;
return dtRes;
}
}
//As a fall-back, just parse it as-is
dtRes = DateTime.Parse(str);
//Assume it has time, as otherwise we'd catch the date-only above
bOutTimePresent = true;
return dtRes;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With