Converting a String to DateTime

后端 未结 17 2637
南方客
南方客 2020-11-21 06:12

How do you convert a string such as 2009-05-08 14:40:52,531 into a DateTime?

17条回答
  •  Happy的楠姐
    2020-11-21 06:34

    Different cultures in the world write date strings in different ways. For example, in the US 01/20/2008 is January 20th, 2008. In France this will throw an InvalidFormatException. This is because France reads date-times as Day/Month/Year, and in the US it is Month/Day/Year.

    Consequently, a string like 20/01/2008 will parse to January 20th, 2008 in France, and then throw an InvalidFormatException in the US.

    To determine your current culture settings, you can use System.Globalization.CultureInfo.CurrentCulture.

    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);  
    

提交回复
热议问题