Need parse dd.MM.yyyy to DateTime using TryParse

前端 未结 8 1813
孤街浪徒
孤街浪徒 2021-01-17 09:51

I need to parse string to DateTime. The string is always in the following format

\"10.10.2010\" That means dd.MM.yyyy, separated with dots.

I want to use Dat

8条回答
  •  忘掉有多难
    2021-01-17 10:35

    I have found that jquery datepicker will add non-printable characters in the string. So, when you try to convert to another format, it will throw an invalid date error every time. In my case, I was just trying to convert it back to a time stamp from whatever culture the user was in at the time. It's a somewhat hacky approach, but it worked for me.

        static public string ToDigitsOnly(string input)
        {
            Regex digitsOnly = new Regex(@"[^\d]");
            return digitsOnly.Replace(input, "");
        }
    
        static private DateTime ConvertDateTimeToDate(string dateTimeString, String langCulture)
        {
    
            System.DateTime result;
    
            string[] dateString = dateTimeString.Split('/');
    
    
            try
            {
                if (langCulture != "en")
                {
                    int Year = Convert.ToInt32(ToDigitsOnly(dateString[2]));
                    int Month = Convert.ToInt32(ToDigitsOnly(dateString[1]));
                    int Day = Convert.ToInt32(ToDigitsOnly(dateString[0]));
                    result = new DateTime(Year, Month, Day, 00, 00, 00);
                }
               else
                {
                    int Year = Convert.ToInt32(dateString[2]);
                    int Month = Convert.ToInt32(dateString[0]);
                    int Day = Convert.ToInt32(dateString[1]);
                    result = new DateTime(Year, Month, Day, 00, 00, 00);
                }
            }
            catch
            {
                // last attempt 
                result = Convert.ToDateTime(dateTimeString, CultureInfo.GetCultureInfo("en-US"));
            }
    
            return result;
        }
    

提交回复
热议问题