0

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.

3
  • 5
    Why you parse your string twice? Commented Sep 26, 2014 at 12:13
  • if try parse returns true - you already have dt and you dont need to Parse again ;) Commented Sep 26, 2014 at 12:14
  • 2
    You need to use the format "dd/M/yyyy"... Commented Sep 26, 2014 at 12:14

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks I have tried your code.It gives me 9/25/2014.But Here in my string 25 is the day ,9 is the month.
@Joydip That is just because the Console.WriteLine(dt.ToString()); (the .ToString() is implied) is defaulting to "mm/dd/yyyy" format. If you change it to Console.WriteLine(dt.ToString("dd/M/yyyy")); it should display as you expect.
@WyattEarp Console.WriteLine(dt.ToString()); isn't exactly "defaulting" to "mm/dd/yyyy" - the result depends on your CurrentCulture (in this case it seems to be en-US)
@Arie In this case it is, that's all I meant. You are correct though.
@WyattEarp I'm just overreacting because of my past mistakes :) There were a few cases when the difference between "default" and "localized" bit me hard (parsing numbers and dates, sorting lists, comparing strings, reading from serial ports...)
2

TryParseExact needs to match exactly.

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

25/9/2014
dd/M/yyyy

Comments

0

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

because

TryParseExact looks for Exact Match

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.