无法在 C# 中解析 "Sept 4, 2020" 或 "sept 4, 2020" 日期字符串

Not able to parse "Sept 4, 2020" or "sept 4, 2020" date string in C#

我用过

DateTime.Parse
DateTime.TryParse
DateTime.TryParseExact
DateTime.ParseExact

没有任何效果。请帮忙

原因是九月的缩写是 Sep 而不是 Sept,至少在我所知道的文化中是这样。你从哪里来?因此,您要么需要在其 Sept 处使用 CultureInfo,要么在输入中将其替换为 Sep

一个更好(比替换)的选择是创建自定义 CultureInfo:

CultureInfo myCulture = (CultureInfo)CultureInfo.InvariantCulture.Clone();
myCulture.DateTimeFormat.AbbreviatedMonthNames = GetCustomAbbreviatedMonthNames();
string[] dates = { "Sept 4, 2020", "sept 4, 2020"};
string[] formats = {"MMM d, yyyy"};
foreach (string s in dates)
    Console.WriteLine(DateTime.TryParseExact(s, formats, myCulture, DateTimeStyles.None, out DateTime dt) ? $"Valid<{dt}>" : $"invalid<{s}>");

static string[] GetCustomAbbreviatedMonthNames()
{
    string[] template = CultureInfo.InvariantCulture.DateTimeFormat.AbbreviatedMonthNames;
    // replace the september but also you might want to do it with the other months as well
    template[8] = "Sept";
    return template;
}

输出:

Valid<04.09.2020 00:00:00>
Valid<04.09.2020 00:00:00>

您可以在 C# 中查看其他 post 关于日期的内容:Date Format in Day, Month Day, Year

你也可以阅读这个:http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

尝试使用:

string date = DateTime.Now.ToString("MMM dd, yyyy");

输出将是

截至今天日期:

Apr 09, 2021

这里是关于 C# 中日期格式的完整指南: https://www.c-sharpcorner.com/blogs/date-and-time-format-in-c-sharp-programming1