Datetime format Issue: String was not recognized as a valid DateTime

前端 未结 8 638

I want to format the input string into MM/dd/yyyy hh:mm:ss format in C#.
The input string is in format MM/dd/yyyy hh:mm:ss
For example :

相关标签:
8条回答
  • 2020-12-03 09:03

    change the culture and try out like this might work for you

    string[] formats= { "MM/dd/yyyy HH:mm" }
    var dateTime = DateTime.ParseExact("04/30/2013 23:00", 
         formats, new CultureInfo("en-US"), DateTimeStyles.None);
    

    Check for details : DateTime.ParseExact Method (String, String[], IFormatProvider, DateTimeStyles)

    0 讨论(0)
  • 2020-12-03 09:03

    You may use this type format (get formatted data from sql server)


    FORMAT(convert(datetime,'16/04/2018 10:52:20',103),'dd/MM/yyyy HH:mm:ss', 'en-us')


    CONVERT(VARCHAR,convert(datetime,'16/04/2018 10:52:20',103), 120)

    0 讨论(0)
  • 2020-12-03 09:12
    DateTime dt1 = DateTime.ParseExact([YourDate], "dd-MM-yyyy HH:mm:ss",  
                                               CultureInfo.InvariantCulture);
    

    Note the use of HH (24-hour clock) rather than hh (12-hour clock), and the use of InvariantCulture because some cultures use separators other than slash.

    For example, if the culture is de-DE, the format "dd/MM/yyyy" would expect period as a separator (31.01.2011).

    0 讨论(0)
  • 2020-12-03 09:16

    Your date time string doesn't contains any seconds. You need to reflect that in your format (remove the :ss).
    Also, you need to specify H instead of h if you are using 24 hour times:

    DateTime.ParseExact("04/30/2013 23:00", "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture)
    

    See here for more information:

    Custom Date and Time Format Strings

    0 讨论(0)
  • 2020-12-03 09:26

    You can use DateTime.ParseExact() method.

    Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.

    DateTime date = DateTime.ParseExact("04/30/2013 23:00", 
                                        "MM/dd/yyyy HH:mm", 
                                        CultureInfo.InvariantCulture);
    

    Here is a DEMO.

    hh is for 12-hour clock from 01 to 12, HH is for 24-hour clock from 00 to 23.

    For more information, check Custom Date and Time Format Strings

    0 讨论(0)
  • 2020-12-03 09:26

    try this:

    string strTime = "04/30/2013 23:00";
    DateTime dtTime;
    if(DateTime.TryParseExact(strTime, "MM/dd/yyyy HH:mm",  
       System.Globalization.CultureInfo.InvariantCulture, 
       System.Globalization.DateTimeStyles.None, out dtTime))
     {
        Console.WriteLine(dtTime);
     }
    
    0 讨论(0)
提交回复
热议问题