Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define DateTime parse format for general date format with optional time part?

What is the right DateTime format to parse a date from string in general date format ("G") with optional time part ("d")?

I can have two types of dates:

  1. "12/13/2012 6:30:00 PM"
  2. "3/29/2013"

How to parse them in unified way? Right now I'm trying to parse with "G" format and then if it not parsed with "d" format.

like image 605
Alexey Strakh Avatar asked Dec 14 '22 19:12

Alexey Strakh


2 Answers

If your CurrentCulture supports MM/dd/yyyy h:mm:ss tt (I assume your LongTimePattern has h) and M/dd/yyyy (I assume your ShortDatePattern has M) as standard date and time format, using DateTime.TryParse(String, out DateTime) method can solve all your problems.

string s = "";
DateTime dt;
if (DateTime.TryParse(s, out dt))
{
    // Your string parsed successfully.
}

If these formats doesn't standard date and time format for your CurrentCulture, using DateTime.TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) overload can be the best choice because it takes formats part as a string array. That means, you can provide multiple formats and your string will be parsed with first successful match.

string s = "";
string[] formats = { "MM/dd/yyyy h:mm:ss tt", "M/dd/yyyy" };
DateTime dt;
if (DateTime.TryParseExact(s, formats, CultureInfo.CurrentCulture,
                           DateTimeStyles.None, out dt))
{
    // Your string parsed with one of speficied format.
}

Be careful when you parse string that have "/" custom format specifier. It has a special meaning of replace me with current culture or specified culture date separator. That means if your CurrentCulture's DateSeparator property is not /, your parsing operation will fail even if your string and formats are the same format.

like image 156
Soner Gönül Avatar answered Dec 17 '22 09:12

Soner Gönül


Just use DateTime.Parse() or if you want to do a safe parse attempt DateTime.TryParse()

DateTime dt1, dt2;
dt1 = DateTime.Parse("12/13/2012 6:30:00 PM");
dt2 = DateTime.Parse("3/29/2013");

OR

DateTime.TryParse("12/13/2012 6:30:00 PM", out dt1);
DateTime.TryParse("3/29/2013", out dt2);

You only have to use DateTime.ParseExact() or provide the format if it differs from the accepted formats that DateTime.Parse() accepts, or if you only allow one particular format.

like image 24
Jeffrey Wieder Avatar answered Dec 17 '22 08:12

Jeffrey Wieder