How do I convert string into Date?

Category: System, viewed: 1K time(s).

In this example you'll see how to convert a string of date and time information into a DateTime object. To convert a string into DateTime we use the DateTime.ParseExact() method or the DateTime.Parse() method.

using System;
using System.Globalization;

namespace Kodecsharp.Example.System {
    class StringToDate {
        
        [STAThread]
        public static void Main(string[] args) {
            string dateTimeInfo = "2009-01-01 12:50:50,350";

            //
            // Convert string information into DateTime using 
            // DateTime.ParseExact() method.
            //
            DateTime dateTime = DateTime.ParseExact(dateTimeInfo, 
                "yyyy-MM-dd HH:mm:ss,fff", 
                CultureInfo.InvariantCulture);

            //
            // Print the new created DateTime object.
            //
            Console.WriteLine("Date: " + 
                string.Format("{0:yyyy-MM-dd HH:mm:ss,fff}", dateTime));

            Console.ReadLine();
        }
    }
}
Powered by Disqus