Converting 8 digit number to DateTime Type
Use DateTime.ParseExact()
with a format specifier of "ddMMyyyy"
or "MMddyyyy"
.
CultureInfo provider = CultureInfo.InvariantCulture;
string dateString = "08082010";
string format = "MMddyyyy";
DateTime result = DateTime.ParseExact(dateString, format, provider);
This will work.
I was just trying to do the same thing, and I'd have to agree with Ignacio's approach. The answer that was accepted works but the ParseExact
method throws an exception in the event that the date string is invalid, while the TryParseExact
method will just return false
. Example:
using System.Globalization;
// ...
string dateString = "12212010";
string format = "MMddyyyy";
DateTime dateStarted;
if (!DateTime.TryParseExact(dateString, format, null, DateTimeStyles.None, out dateStarted))
dateStarted = DateTime.Now;