如何为带有可选时间部分的通用日期格式定义DateTime解析格式? [英] How to define DateTime parse format for general date format with optional time part?
问题描述
什么是正确的 DateTime
格式以解析具有通用日期格式("G")
的字符串中的日期以及可选的时间部分("d")
?
我可以有两种日期类型:
-
"2012年12月13日下午6:30:00"
-
"2013年3月29日"
如何统一解析它们?现在,我正在尝试使用"G"
格式进行解析,然后如果不使用"d"
格式进行解析.
如果您的 LongTimePattern
具有 h
)和 M/dd/yyyy
(我假设您的 DateTime.TryParse(String,out DateTime)
方法可以解决所有问题.
string s =";DateTime dt;如果(DateTime.TryParse(s,out dt)){//您的字符串已成功解析.}
如果这些格式不是 当您解析具有 What is the right I can have two types of dates: How to parse them in unified way?
Right now I'm trying to parse with If your If these formats doesn't standard date and time format for your Be careful when you parse string that have 这篇关于如何为带有可选时间部分的通用日期格式定义DateTime解析格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! CurrentCulture
的标准日期和时间格式,请使用 "/"的字符串时,请当心
自定义格式说明符.它具有用当前区域性或指定的区域性日期分隔符替换我的特殊含义.这意味着,如果您的 CurrentCulture
的 DateSeparator
属性不是/
,如果您的字符串和格式相同,则解析操作也会失败甚至.>DateTime
format to parse a date from string in general date format ("G")
with optional time part ("d")
?
"12/13/2012 6:30:00 PM"
"3/29/2013"
"G"
format and then if it not parsed with "d"
format.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.
}
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.
}
"/"
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.