Converts the specified string representation of a date and time to its equivalent. - CSharp System

CSharp examples for System:DateTime Format

Description

Converts the specified string representation of a date and time to its equivalent.

Demo Code


using System.Globalization;
using System;//from w  w  w  .j ava  2  s.c o m

public class Main{
        #endregion


        #region Methods

        ///// <summary>
        ///// The supported formats used to parse strings.
        ///// </summary>
        //public static string[] GetParseFormats()
        //{
        //  return (string[]) parseFormats.Clone();
        //}

        /// <summary>
        /// Converts the specified string representation of a date and time to its <see cref="DateTime"/> equivalent. 
        /// </summary>
        /// <remarks>
        /// Accepted formats for parsing are "dd MMM yyyy HH:mm:ss.ff", "yyyy-MM-ddTHH:mm:ss", "dd MMM yyyy hh:mm tt", "dd MMM yyyy hh:mm:ss tt", "dd MMM yyyy HH:mm:ss", "dd MMM yyyy HH:mm" and "dd MMM yyyy". <see cref="DateTime.ParseExact(string,string[],IFormatProvider,DateTimeStyles)"/> is used to attempt to parse <paramref name="s"/>.
        /// </remarks>
        /// <param name="s">A string containing a date and (optionally) time to convert.</param>
        /// <returns>A <see cref="DateTime"/> equivalent to the date and time contained in <paramref name="s"/>.</returns>
        /// <exception cref="FormatException"><paramref name="s"/> cannot be parsed.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="s"/> is a null reference.</exception>
        /// <exception cref="ArgumentException"><paramref name="s"/> is <see cref="string.Empty"/>.</exception>
        public static DateTime Parse(string s)
        {
            Guard.ArgumentNotNullOrEmptyString(s, "s");
            try
            {
                return DateTime.ParseExact(s, parseFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None);
            }
            catch (FormatException formatException)
            {
                throw new FormatException(string.Format("{0}. Value = {1}", formatException.Message, s), formatException);
            }
        }
}

Related Tutorials