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

佐手、 提交于 2021-02-07 19:39:39

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/26132505/how-to-define-datetime-parse-format-for-general-date-format-with-optional-time-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!