How do I convert string into Date?

Category: System, viewed: 348 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();
        }
    }
}
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Our Friends

Statistics

Locations of visitors to this page