我在使用时遇到了麻烦 DateTime.Parse
我正在处理各种格式的日期,其中一些是格式January 11th或February 22nd等等.
DateTime.Parse 尝试解析这些日期时抛出异常.
我想知道在DateTime中是否存在我缺少的内置功能,就像我可以设置的标志,这将使Parse以更可接受的方式运行.
我知道这可用一个相对简单的正则表达式解决,而且我已经有一个模糊匹配我写的日期的类,但是我想知道是否有内置的方法来执行这种提取,因为它将从长远来看,比重新发明轮子更容易维护.
Hab*_*bib 14
.Net框架中没有内置任何内容来解析格式January 11th or February 22nd等的日期.您必须删除后缀字符然后才能使用 DateTime.TryParseExact.
对于后缀日期st,th你可以使用string.Replace删除的部分,然后使用DateTime.TryParseExact.喜欢.
string str = "1st February 2013";
DateTime dtObject;
string replacedStr = str.Substring(0,4)
.Replace("nd","")
.Replace("th","")
.Replace("rd","")
.Replace("st","")
+ str.Substring(4);
if (DateTime.TryParseExact(replacedStr,
"dd MMMMM yyyy",
CultureInfo.InstalledUICulture,
DateTimeStyles.None,
out dtObject))
{
//valid date
}
Run Code Online (Sandbox Code Playgroud)
对于多种格式,您可以在字符串数组中指定格式,稍后您可以使用它.它返回一个bool值,指示解析是否成功.
来自MSDN的示例:
string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt",
"MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss",
"M/d/yyyy hh:mm tt", "M/d/yyyy hh tt",
"M/d/yyyy h:mm", "M/d/yyyy h:mm",
"MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"};
string[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM",
"5/1/2009 6:32:00", "05/01/2009 06:32",
"05/01/2009 06:32:00 PM", "05/01/2009 06:32:00"};
DateTime dateValue;
foreach (string dateString in dateStrings)
{
if (DateTime.TryParseExact(dateString, formats,
new CultureInfo("en-US"),
DateTimeStyles.None,
out dateValue))
Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
else
Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
Run Code Online (Sandbox Code Playgroud)
小智 14
这是一个非常古老的问题,但对于仍然在研究复杂的自然语言日期解析的人,我建议使用nChronic,这是一个令人惊叹的(基于ruby的)慢性日期解析器的.NET端口.
它的来源是: nChronic Github
这也是在为的NuGet慢性:慢性中的NuGet
使用此库的一些非常简单的示例代码将是这样的:
using Chronic;
var parser = new Chronic.Parser ();
Span ParseObj;
DateTime ParsedDateTime;
ParseObj = parser.Parse ("January 11th");
ParsedDateTime = ParseObj.Start;
Run Code Online (Sandbox Code Playgroud)
以下是它可以处理的一些示例:
简单
复杂
具体日期
特定时间(以上许多时间增加)
等等
我有类似的问题这里有更好的方法
stringdate="August 19th 2000"
string pattern = @"\b(\d+)(?:st|nd|rd|th)\b";
Regex rgx = new Regex(pattern);
DateTime.Parse(String.Format("{0:MMMM, d, yyyy}", rgx.Replace(stringdate, "$1"))
**result** {19/08/2000 00:00:00} System.DateTime
Run Code Online (Sandbox Code Playgroud)
从Microsoft和regex 删除序数以及如何可视化各种 DateTime 格式的显示方式?
编辑
如果未指定年份:
stringdate= rgx.Replace(stringdate, "$1");
DateTime datetime;
if (!DateTime.TryParseExact(stringdate, "MMMM dd yyyy", System.Globalization.DateTimeFormatInfo.InvariantInfo, System.Globalization.DateTimeStyles.None, out datetime))
{
// assuming no gap exist
datetime = DateTime.Parse(stringdate += " "+DateTime.Now.Year);
}
Run Code Online (Sandbox Code Playgroud)
现在,如果输入字符串 text 是"June 11th",它将是 11/6/2021。
在DateTime 文档中有更多的函数和方法来处理日期。
如果您根本不想要年份,则可以添加以下行:
datetime.ToString("MM/dd");
Run Code Online (Sandbox Code Playgroud)
现在输出将是“11/6”