コード例 #1
0
        /// <summary>Parses the date value using the given date formats.</summary>
        /// <remarks>Parses the date value using the given date formats.</remarks>
        /// <param name="dateValue">the date value to parse</param>
        /// <param name="dateFormats">the date formats to use</param>
        /// <param name="startDate">
        /// During parsing, two digit years will be placed in the range
        /// <code>startDate</code> to <code>startDate + 100 years</code>. This value may
        /// be <code>null</code>. When <code>null</code> is given as a parameter, year
        /// <code>2000</code> will be used.
        /// </param>
        /// <returns>the parsed date or null if input could not be parsed</returns>
        public static DateTime ParseDate(string dateValue, string[] dateFormats, DateTime
                                         startDate)
        {
            Args.NotNull(dateValue, "Date value");
            string[] localDateFormats = dateFormats != null ? dateFormats : DefaultPatterns;
            DateTime localStartDate   = startDate != null ? startDate : DefaultTwoDigitYearStart;
            string   v = dateValue;

            // trim single quotes around date if present
            // see issue #5279
            if (v.Length > 1 && v.StartsWith("'") && v.EndsWith("'"))
            {
                v = Sharpen.Runtime.Substring(v, 1, v.Length - 1);
            }
            foreach (string dateFormat in localDateFormats)
            {
                SimpleDateFormat dateParser = DateUtils.DateFormatHolder.FormatFor(dateFormat);
                dateParser.Set2DigitYearStart(localStartDate);
                ParsePosition pos    = new ParsePosition(0);
                DateTime      result = dateParser.Parse(v, pos);
                if (pos.GetIndex() != 0)
                {
                    return(result);
                }
            }
            return(null);
        }