Reputation: 16219
I'm trying to convert string
formatted like 09172014
into DateTime
string mydate = "09172014";
DateTime newDate = DateTime.Parse(mydate);
but failed to do so. I know it must be easy trick but getting wierd errors :(`
Upvotes: 0
Views: 582
Reputation: 66
Just try this :
string myDate = "09172017"
DateTime newDate = DateTime.ParseExact(myDate, "MMddyyyy", CultureInfo.InvariantCulture);
then you can convert MMddyyyy date to DateTime.
Upvotes: 1
Reputation: 596
Try ParseExact:
string dateString, format;
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
// Parse date and time with custom specifier.
dateString = "09172014";
format = "MMddyyyy";
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}
More info: http://msdn.microsoft.com/en-us/library/w2sa9yss(v=vs.110).aspx
Upvotes: 0
Reputation: 1041
You should use ParseExact:
var date = DateTime.ParseExact("09172014", "MMddyyyy", System.Globalization.CultureInfo.InvariantCulture);
Upvotes: 3
Reputation: 26856
You should provide format.
string mydate = "09172014";
DateTime date = DateTime.ParseExact(mydate, "MMddyyyy", CultureInfo.InvariantCulture);
Upvotes: 3
Reputation: 3875
DateTime dt=DateTime.ParseExact(mydate, "MMddyyyy", CultureInfo.InvariantCulture);
Should do the trick for you.
Upvotes: 0