简体   繁体   中英

DateTime.ParseExact FormatException String was not recognized as a valid DateTime

I'm completely stumped on this one. As far as I can see the documentation and other posts on SO I've read say this should work. I must be missing something silly, but I just cannot see it.

I get a FormatException with the message "String was not recognized as a valid DateTime." on the following line of code:

return DateTime.ParseExact(value, DateFormat, null,
                           DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.AssumeUniversal);
  • value is "11/04/2013"
  • DateFormat is "dd/MM/yyyy"
  • The current culture is en-GB
  • I've tried various variants of DateTimeStyles but to no effect.

My original intent was for the format ddd, dd/MMM/yyyy but that didn't work either (the value in that instance was Tue, 30/Apr/2013 )

I've also tried forcing the culture to en-GB by passing in new CultureInfo("en-GB") instead of the null

I also extracted the code into its own console application to see if there was different about the environment (ASP.NET MVC 3)

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var DateFormat = "dd/MM/yyyy";
            var value = "30/04/2013";
            var culture = new CultureInfo("en-GB");
            var result = DateTime.ParseExact(value, DateFormat, culture,
                           DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.AssumeUniversal);
            Console.WriteLine("\"{0}\" as \"{1}\" ==> {2}", value, DateFormat, result);
            Console.ReadKey();
        }
    }
}

And that still gives me the same error.

Does this work

 string myDate = "30-12-1899 07:50:00:AM";
DateTime dt1 = DateTime.ParseExact(myDate, "dd-MM-yyyy hh:mm:ss:tt", 
                                           CultureInfo.InvariantCulture)
string myDate = "30-12-1899 07:50:00:AM";
DateTime dt1 = DateTime.ParseExact(myDate, "dd-MM-yyyy HH:mm:ss:tt",  
                                           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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM