Convert string to Datetime by format - CSharp System

CSharp examples for System:DateTime Format

Description

Convert string to Datetime by format

Demo Code


using System.Text;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System;/*from ww  w .j  av  a 2s.  c o m*/

public class Main{
        /// <summary>
        /// Convert Datetime
        /// </summary>
        /// <param name="DateTime">Datetime to convert</param>
        /// <param name="DateFormat">string format date</param>
        /// <returns>string Datetime format as DateFormat</returns>
        public static string ConvertDateTime(DateTime DateTime, string DateFormat)
        {
            return DateTime.ToString(DateFormat);
        }
        /// <summary>
        /// Convert Datetime
        /// </summary>
        /// <param name="DateTime">Datetime to convert</param>
        /// <returns>Default dd/MM/yyyy HH:mm:ss</returns>
        public static string ConvertDateTime(DateTime DateTime)
        {
            return ConvertDateTime(DateTime, "dd/MM/yyyy HH:mm:ss tt");
        }
        /// <summary>
        /// Convert string Datetime
        /// </summary>
        /// <param name="DateTime">string Datetime to convert</param>
        /// <param name="DateFormat">string format date</param>
        /// <returns>string Datetime format as DateFormat</returns>
        public static string ConvertDateTime(string DateTime, string DateFormat)
        {
            DateTime dt = new DateTime();
            try
            {
                dt = Convert.ToDateTime(DateTime);
            }
            catch { }
            return dt.ToString(DateFormat);
        }
        /// <summary>
        /// Convert string Datetime
        /// </summary>
        /// <param name="DateTime">string Datetime to convert</param>
        /// <returns>Default dd/MM/yyyy HH:mm:ss</returns>
        public static string ConvertDateTime(string DateTimes) 
        {
            try
            {
                if (DateTimes.Length == 0)
                {
                    DateTimes = DateTime.Now.ToString();
                }
                else
                {
                    DateTimes = DateTimes;
                }
                return ConvertDateTime(DateTimes, "dd/MM/yyyy hh:mm:ss tt");
            }
            catch 
            {
                return DateTimes;
            }
        }
}

Related Tutorials