Joydip
Joydip

Reputation: 41

String to datetime in C#

I have a string strdate="25/9/2014" here in dd/MM/yyyy format.I want to parse it in date time like below

DateTime dt;
            if (DateTime.TryParseExact(strDate, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dt))
            {
                dt = DateTime.Parse(strDate);
            }

            Console.WriteLine(dt);

But it can not parse.Please help me.

Upvotes: 0

Views: 106

Answers (3)

Matthew Watson
Matthew Watson

Reputation: 109537

Two things:

1: Your string format should be "dd/M/yyyy" (a double MM will require two month digits; a single M will allow 1 or 2 month digits).

2: You are parsing the date string twice.

Change your code to:

DateTime dt;

if (DateTime.TryParseExact(strDate, "dd/M/yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dt))
{
    Console.WriteLine(dt.ToString("dd/M/yyyy"));
}
else
{
    Console.WriteLine("Can't parse it.");
}

[EDIT] Changed the Console.WriteLine() so that it outputs in the specific "dd/M/yyyy" format rather than using the local system locale.

Upvotes: 9

user4079229
user4079229

Reputation:

Change "dd/MM/yyyy" to "dd/M/yyyy"

because

TryParseExact looks for Exact Match

Upvotes: 0

TryParseExact needs to match exactly.

In your case try dd/M/yyyy as your input is

25/9/2014
dd/M/yyyy

Upvotes: 2

Related Questions