简体   繁体   中英

Parse a string to a DateTime object

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?

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 .

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM