Christopher: .NET: DateTime.Parse

Beitrag lesen

Hi,

public static DateTime? Parse(string value)
=> Wie schaut den dein Value den aus und wo kommt es den her???

Typisch, da vergisst man mal wieder das wichtigste Detail ;)

Es stammt von einem DataTable und ist - abhaengig von der
gewaehlten Sprache - zB 1/25/2007 2:00:31 PM.

Allerdings habe ich jetzt eine temporaere Loesung erstellt.
Da die Webanwendung lediglich fuenf Sprachen unterstuetzt
versuche ich jedes Datum in die verfuegbaren Datumsformate
zu casten. Angefangen beim Default-Datum.

  
/// <summary>  
        /// Parses a string to a DateTime in consideration of a given DateTimeFormat  
        /// </summary>  
        /// <param name="value">the datetime value as string</param>  
        /// <param name="dtf">the localized DateTimeFormat</param>  
        /// <returns>DateTime if possible, otherwise null</returns>  
        public static DateTime? Parse(string value, DateTimeFormatInfo dtf)  
        {  
            DateTime? ret = null;  
            try  
            {  
                DateTime tmp = DateTime.Parse(value, dtf);  
                ret = tmp;  
            } catch(Exception) {}  
            return ret;  
        }  
  
        /// <summary>  
        /// Tries to parse a given string representation of a DateTime to  
        /// a valid DateTime-object  
        /// </summary>  
        /// <param name="value">the value to parse</param>  
        /// <returns>DateTime represenation of $value if possible, otherwise null</returns>  
        public static DateTime? Parse(string value)  
        {  
            DateTime? ret = null;  
  
            ret = Parse(value, CultureInfo.GetCultureInfo("en-GB").DateTimeFormat);  
  
            if (ret == null)  
                ret = Parse(value, CultureInfo.GetCultureInfo("en-US").DateTimeFormat);  
  
            if (ret == null)  
                ret = Parse(value, CultureInfo.GetCultureInfo("de-DE").DateTimeFormat);  
  
            if (ret == null)  
                ret = Parse(value, CultureInfo.GetCultureInfo("en-IT").DateTimeFormat);  
  
            if (ret == null)  
                ret = Parse(value, CultureInfo.GetCultureInfo("fr-FR").DateTimeFormat);  
  
            if (ret == null)  
                ret = Parse(value, CultureInfo.GetCultureInfo("es-ES").DateTimeFormat);  
  
            if(ret==null)  
                ExceptionHandler.MailException("Can not convert '" + value + "' to a valid DateTime.", false);  
  
            return ret;  
        }