Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if time part was present when parsing with DateTime

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?

like image 830
c00000fd Avatar asked Nov 23 '22 20:11

c00000fd


1 Answers

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;
}
like image 157
c00000fd Avatar answered Nov 26 '22 09:11

c00000fd