Matthew
Matthew

Reputation: 217

.NET DateTime.Parse

When trying to use the parse method on the DateTime class, I get an exception thrown:

String was not recognized as a valid DateTime.

Examples of other strings:

26/10/2009 8:47:39 AM
26/10/2009 8:00:41 AM
26/10/2009 7:48:35 AM

The weird thing is, I am sure it has worked before.

Upvotes: 9

Views: 21297

Answers (7)

efsandino
efsandino

Reputation: 975

I have to solve some really strange date format coming from other system... In this example is for SPANISH format ...

string input="07/06/2019 07:01:54 p. m.";


public static DateTime ParseSpanishDate(string input)
{
    string normalized = input.Replace("a. m.", "AM").Replace("p. m.", "PM");
    normalized = normalized.Replace("12:00:00 AM", "00:00:00 AM");
    return  DateTime.Parse(normalized, CultureInfo.GetCultureInfo("es"));
}

Upvotes: 0

Ron Klein
Ron Klein

Reputation: 9440

I second @Lucero, Parse uses current thread's culture info etc. See also the opposite direction: a ToString question in this context.

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838066

You're probably using the wrong culture. The month cannot be 26, so it's not a US timestamp. This works though:

using System;
using System.Globalization;

class Program
{
    static void Main(string[] args)
    {
        DateTime dateTime = DateTime.Parse("26/10/2009 8:47:39 AM",
            CultureInfo.GetCultureInfo("en-GB"));
    }
}

Upvotes: 3

Fredrik Mörk
Fredrik Mörk

Reputation: 158309

Parsing strings into DateTime object is almost always a pain. If you know for certain that they will always have the format as your examples do, this should work:

string input = "26/10/2009 8:00:41 AM";
DateTime dateTime = DateTime.ParseExact(input, "dd/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);

Upvotes: 25

Justin Niessner
Justin Niessner

Reputation: 245399

Either call DateTime.Parse() with the culture as a parameter or call DateTime.ParseExact() with the date, the exact format of the date to parse, and the culture:

DateTime.ParseExact()

Upvotes: 2

Lucero
Lucero

Reputation: 60190

Parse takes regional settings (culture of current thread) into account. Therefore, I'd use ParseExact and specify the correct format explicitly with an invariant culture (or the culture you need, eg. en-US, for AM/PM).

Upvotes: 12

Pharabus
Pharabus

Reputation: 6062

Has the culure changed on the machine? 26/10/2009 is a good UK date but a bad US date (for instance)

Upvotes: 2

Related Questions