Home > DeveloperSection > Forums > Convert a string to a date in .net
Chintoo Semi

Total Post:135

Points:947
Posted on    November-14-2013 3:09 AM

 C# C# 
Ratings:


 1 Reply(s)
 943  View(s)
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?


ezra heywood
ezra heywood

Total Post:145

Points:1019
Posted on    November-14-2013 4:56 AM

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

Don't want to miss updates? Please click the below button!

Follow MindStick