Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net-4.0

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.

like image 798
Colin Mackay Avatar asked Apr 09 '13 11:04

Colin Mackay


2 Answers

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)
like image 102
Rohit Avatar answered Oct 02 '22 01:10

Rohit


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

like image 21
Diorrini11 Avatar answered Oct 02 '22 00:10

Diorrini11