Reputation: 8266
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?
Upvotes: 0
Views: 166
Reputation: 3794
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/
Upvotes: 1
Reputation: 498934
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
.
Upvotes: 10