convert string to a DateTime value if possible. - CSharp System

CSharp examples for System:DateTime Convert

Description

convert string to a DateTime value if possible.

Demo Code


using System.Xml;
using System.Web;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;/*from  w ww  .  j  a  v a  2s.  c o m*/

public class Main{
        /// <summary>
        /// convert string to a DateTime value if possible.
        /// </summary>
        /// <param name="theSource">the souce string</param>
        /// <param name="theDefault">the replace value if string could not convert to DateTime</param>
        /// <returns>a DateTime value</returns>
        public static DateTime ToDateTime(this string theSource, DateTime theDefault)
        {
            DateTime tempValue;
            return !string.IsNullOrEmpty(theSource) && DateTime.TryParse(theSource, out tempValue) ? tempValue : theDefault;
        }
        /// <summary>
        /// convert string to a DateTime value if possible, if failed, return DateTime.MinValue as default value.
        /// </summary>
        /// <param name="theSource">the souce string</param>
        /// <returns>a DateTime value</returns>
        public static DateTime ToDateTime(this string theSource)
        {
            return theSource.ToDateTime(DateTime.MinValue);
        }
}

Related Tutorials