0

I'm trying to parse a String into a DateTime object but it seems to always default the month to 1. So let's say I give it a string 30/05/1970 it ends up being converted to DateTime object with the month value equal to 1.

Here's the code:

    public static DateTime ToDateTime(this String value, String format)
    {
        Contract.Requires(!String.IsNullOrEmpty(value));
        Contract.Requires(!String.IsNullOrEmpty(format));

        DateTime date;
        if (DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
        {
            return date;
        }           

        throw new ArgumentException("Input value is not a valid date.");
    }

Note that the format that is being passed to the method is dd/mm/yyyy.

Any thoughts?

0

2 Answers 2

10

You are using the wrong format specifier for months.

It is MM not mm. You are parsing months as minutes at the moment.

Use dd/MM/yyyy.

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

3 Comments

I've been stuck with this for like 2 hours! I tried all sorts of things but I never thought of changing the format. Thanks for pointing this out! Much appreciated :)
@Kassem: you should probably mark this as a correct answer then
@MiMo: Yup, I did. I just had to wait until StackOverflow allows it.
1

You're probably specifying an incorrect format.

Do this instead

var dt= ToDateTime("30/05/1970", "dd/MM/yyyy");

And take a look at this: http://www.csharp-examples.net/string-format-datetime/

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.