CONVERT A STRING TO A DATE IN .NET

Chintoo Semi

Total Post:135

Points:947
Posted by  Chintoo Semi
C# 
C#
 1278  View(s)
Ratings:
Rate this:
I'm reading text from a flat file in c# and need to test whether certain values are dates. They could be in either YYYYMMDD format or MM/DD/YY format. What is the simplest way to do this in .Net?
  1. ezra heywood

    Post:145

    Points:1019
    Re: Convert a string to a date in .net

    Hi chintoo,

    string dateTime = "01/08/2008 14:50:50.42";

                DateTime dt = Convert.ToDateTime(dateTime);

                Console.WriteLine("Year: {0}, Month: {1}, Day: {2}, Hour: {3}, Minute: {4}, Second: {5}, Millisecond: {6}",

                                  dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Millisecond);

                // Specify exactly how to interpret the string.

                IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);


                // Alternate choice: If the string has been input by an end user, you might  

                // want to format it according to the current culture: 

                // IFormatProvider culture = System.Threading.Thread.CurrentThread.CurrentCulture;

                DateTime dt2 = DateTime.Parse(dateTime, culture, System.Globalization.DateTimeStyles.AssumeLocal);

                Console.WriteLine("Year: {0}, Month: {1}, Day: {2}, Hour: {3}, Minute: {4}, Second: {5}, Millisecond: {6}",

                                  dt2.Year, dt2.Month, dt2.Day, dt2.Hour, dt2.Minute, dt2.Second, dt2.Millisecond

    /* Output (assuming first culture is en-US and second is fr-FR):

        Year: 2008, Month: 1, Day: 8, Hour: 14, Minute: 50, Second: 50, Millisecond: 420

    Year: 2008, Month: 8, Day: 1, Hour: 14, Minute: 50, Second: 50, Millisecond: 420

    Press any key to continue . . .

     */

      Modified On Apr-04-2016 11:21:28 PM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!