Converting a String to DateTime

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

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

相关标签:
17条回答
  • 2020-11-21 06:29

    Nobody seems to implemented an extension method. With the help of @CMS's answer:

    Working and improved full source example is here: Gist Link

    namespace ExtensionMethods {
        using System;
        using System.Globalization;
    
        public static class DateTimeExtensions {
            public static DateTime ToDateTime(this string s, 
                      string format = "ddMMyyyy", string cultureString = "tr-TR") {
                try {
                    var r = DateTime.ParseExact(
                        s: s,
                        format: format,
                        provider: CultureInfo.GetCultureInfo(cultureString));
                    return r;
                } catch (FormatException) {
                    throw;
                } catch (CultureNotFoundException) {
                    throw; // Given Culture is not supported culture
                }
            }
    
            public static DateTime ToDateTime(this string s, 
                        string format, CultureInfo culture) {
                try {
                    var r = DateTime.ParseExact(s: s, format: format, 
                                            provider: culture);
                    return r;
                } catch (FormatException) {
                    throw;
                } catch (CultureNotFoundException) {
                    throw; // Given Culture is not supported culture
                }
    
            }
    
        }
    }
    
    namespace SO {
        using ExtensionMethods;
        using System;
        using System.Globalization;
    
        class Program {
            static void Main(string[] args) {
                var mydate = "29021996";
                var date = mydate.ToDateTime(format: "ddMMyyyy"); // {29.02.1996 00:00:00}
    
                mydate = "2016 3";
                date = mydate.ToDateTime("yyyy M"); // {01.03.2016 00:00:00}
    
                mydate = "2016 12";
                date = mydate.ToDateTime("yyyy d"); // {12.01.2016 00:00:00}
    
                mydate = "2016/31/05 13:33";
                date = mydate.ToDateTime("yyyy/d/M HH:mm"); // {31.05.2016 13:33:00}
    
                mydate = "2016/31 Ocak";
                date = mydate.ToDateTime("yyyy/d MMMM"); // {31.01.2016 00:00:00}
    
                mydate = "2016/31 January";
                date = mydate.ToDateTime("yyyy/d MMMM", cultureString: "en-US"); 
                // {31.01.2016 00:00:00}
    
                mydate = "11/شعبان/1437";
                date = mydate.ToDateTime(
                    culture: CultureInfo.GetCultureInfo("ar-SA"),
                    format: "dd/MMMM/yyyy"); 
             // Weird :) I supposed dd/yyyy/MMMM but that did not work !?$^&*
    
                System.Diagnostics.Debug.Assert(
                   date.Equals(new DateTime(year: 2016, month: 5, day: 18)));
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-21 06:29

    You could also use DateTime.TryParseExact() as below if you are unsure of the input value.

    DateTime outputDateTimeValue;
    if (DateTime.TryParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out outputDateTimeValue))
    {
        return outputDateTimeValue;
    }
    else
    {
        // Handle the fact that parse did not succeed
    }
    
    0 讨论(0)
  • 2020-11-21 06:30

    Try the below, where strDate is your date in 'MM/dd/yyyy' format

    var date = DateTime.Parse(strDate,new CultureInfo("en-US", true))
    
    0 讨论(0)
  • 2020-11-21 06:34

    You have basically two options for this. DateTime.Parse() and DateTime.ParseExact().

    The first is very forgiving in terms of syntax and will parse dates in many different formats. It is good for user input which may come in different formats.

    ParseExact will allow you to specify the exact format of your date string to use for parsing. It is good to use this if your string is always in the same format. This way, you can easily detect any deviations from the expected data.

    You can parse user input like this:

    DateTime enteredDate = DateTime.Parse(enteredString);
    

    If you have a specific format for the string, you should use the other method:

    DateTime loadedDate = DateTime.ParseExact(loadedString, "d", null);
    

    "d" stands for the short date pattern (see MSDN for more info) and null specifies that the current culture should be used for parsing the string.

    0 讨论(0)
  • 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);  
    
    0 讨论(0)
  • 2020-11-21 06:40

    I tried various ways. What worked for me was this:

    Convert.ToDateTime(data, CultureInfo.InvariantCulture);
    

    data for me was times like this 9/24/2017 9:31:34 AM

    0 讨论(0)
提交回复
热议问题