C# 无法使用可变格式分析日期字符串

C# 无法使用可变格式分析日期字符串,c#,datetime,C#,Datetime,我会直截了当地说,我最讨厌的一件事就是和DateTime打交道——很可能是我对文化、时区和全球化缺乏了解 在我的国际级应用程序中,我试图找出构建一个函数的最佳方法,该函数将处理所有格式,而不管传入的格式如何 我想目前我还不能完全确定,为什么我有一个特定的格式,它不会解析成日期,而日期是通过客户端传递的 这是所有的测试暂时,但从来没有减少痛苦的哔哔声 目前,我正在尝试转换en_gb日期,以及附加的标准ISO格式代码片段 string[] formats = { "d/M/yyyy h:mm

我会直截了当地说,我最讨厌的一件事就是和DateTime打交道——很可能是我对文化、时区和全球化缺乏了解

在我的国际级应用程序中,我试图找出构建一个函数的最佳方法,该函数将处理所有格式,而不管传入的格式如何

我想目前我还不能完全确定,为什么我有一个特定的格式,它不会解析成日期,而日期是通过客户端传递的

这是所有的测试暂时,但从来没有减少痛苦的哔哔声

目前,我正在尝试转换en_gb日期,以及附加的标准ISO格式代码片段

string[] formats = {
    "d/M/yyyy h:mm:ss tt", 
    "d/M/yyyy h:mm tt",
    "dd/MM/yyyy hh:mm:ss", 
    "d/M/yyyy h:mm:ss",
    "d/M/yyyy hh:mm tt", 
    "d/M/yyyy hh tt",
    "d/M/yyyy h:mm",
    "d/M/yyyy h:mm",
    "dd/MM/yyyy hh:mm", 
    "dd/m/yyyy hh:mm",
    "yyyy-MM-dd'T'HH:mm:sszzz",
    "dd/MM/yyyy hh:mm:ss UTC"
};

if (DateTime.TryParseExact(val, formats, 
    CultureInfo.CurrentCulture, 
    DateTimeStyles.AllowWhiteSpaces, out dt))
{
    return dt;
}
因此,如果我可以问,为什么2017年6月13日10:25:00 UTC解析,但2017年6月27日16:11:00 UTC失败返回false

我觉得我可能盯着这个看太久了


真正欣赏正确方向的轻推…

您的问题是,您正在匹配的时间是使用h或hh,即12小时时钟时间,即它接受1-12或01-12。如果您要将dd/MM/yyyy HH:MM:ss UTC添加到格式列表中,那么这将能够匹配2017年6月27日16:11:00 UTC。一般来说,我怀疑没有tt说明符的任何东西都可能想要H/HH而不是H/HH,尽管我让您自己来确定您想要什么

在此处找到文档:

请查看此文档

static void FormatDate(string strInputDateTimeValue)
        {
            int day = 0, month = 0, year = 0, hours = 0, minutes = 0, seconds = 0, milliSeconds = 0, dateTimeKind = 0;
            List<string> lstSplittedInputDateTime = (from data in strInputDateTimeValue.Split(' ').ToList() where !string.IsNullOrEmpty(data) select data).ToList();
            if (lstSplittedInputDateTime != null)
            {
                string strDate = lstSplittedInputDateTime[0];//Fetching Only Date Part: Considering date format will be mm/DD/yyyy
                if (!string.IsNullOrEmpty(strDate))
                {
                    month = Convert.ToInt32(strDate.Split('/').ToList()[1]);//Fetch Month
                    day = Convert.ToInt32(strDate.Split('/').ToList()[0]);//Fetch Day
                    year = Convert.ToInt32(strDate.Split('/').ToList()[2]);//Fetch Year
                }
                string strTime = lstSplittedInputDateTime[1];//Fetching Only Time Part
                if (strTime != null)
                {
                    hours = Convert.ToInt32(strTime.Split(':').ToList()[0]);//Fetch Hours
                    minutes = Convert.ToInt32(strTime.Split(':').ToList()[1]);//Fetch Minutes
                    seconds = Convert.ToInt32(strTime.Split(':').ToList()[2]);//Fetch Seconds
                    milliSeconds = Convert.ToInt32(strTime.Split(':').ToList()[3]);//Fetch MilliSeconds
                }
                string strDateTimeKind = lstSplittedInputDateTime[2];//Fetching DateTimeKind
                if (strDateTimeKind != null)
                {
                    if (strDateTimeKind.ToLower() == "utc")
                        dateTimeKind = (int)System.DateTimeKind.Utc;
                    else if (strDateTimeKind.ToLower() == "Local")
                        dateTimeKind = (int)System.DateTimeKind.Local;
                    else
                        dateTimeKind = (int)System.DateTimeKind.Utc;
                }
            }
            DateTime dtFormattedDate = new DateTime(year, month, day, hours, minutes, seconds, (DateTimeKind)dateTimeKind);
            Console.WriteLine("Local: {0}", TimeZoneInfo.ConvertTime(dtFormattedDate, TimeZoneInfo.Local).ToString());
            Console.WriteLine("UTC: {0}", TimeZoneInfo.ConvertTime(dtFormattedDate, TimeZoneInfo.Utc).ToString());
        }

        public void Run()
        {
            FormatDate("27/06/2017  16:11:00 UTC");
            Console.ReadLine();
        }

您最好使用一个专用的库,比如NodaTime,而不是自己尝试重新实现所有这些逻辑。结果,我盯着它看了太久。。。我忽略了什么。竖起大拇指,是的。容易出错。我刚刚注意到,在dd/m/yyyy中,一个月的位置上也有一个小写的m hh:mm,这是我经常出错的地方。谢谢,我也错过了+1虽然我非常感谢您的贡献,但我非常反对过度使用条件句。我觉得你的回答可能有点过分了。永远不会少,谢谢你的时间。