Converting 8 digit number to DateTime Type
I want to convert 8 digit value to a DateTime object. How can I do this?开发者_C百科 For example, if a user enters 08082010 then it should convert it to 08/08/2010, using C#.
CultureInfo provider = CultureInfo.InvariantCulture;
string dateString = "08082010";
string format = "MMddyyyy";
DateTime result = DateTime.ParseExact(dateString, format, provider);
This will work.
Use DateTime.ParseExact()
with a format specifier of "ddMMyyyy"
or "MMddyyyy"
.
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;
Use DateTime.Parse
Full fubar is
private static DateTime FormatDateTimeString(string stringToFormat)
{
var yearStr = stringToFormat.Substring(0,4);
var monthofyearStr = stringToFormat.Substring(4, 2);
var dayofmonthStr = stringToFormat.Substring(6, 2);
var hourStr = stringToFormat.Substring(8, 2);
var minuteStr = stringToFormat.Substring(10, 2);
var year = int.Parse(yearStr);
var monthofyear = int.Parse(monthofyearStr);
var dayofmonth = int.Parse(dayofmonthStr);
var hour = int.Parse(hourStr);
var minute = int.Parse(minuteStr);
if (year > 999 && year < 3000)
if(monthofyear > 0 && monthofyear< 13)
if (dayofmonth > 0 && dayofmonth < 32)
if (hour >= 0 && hour < 24)
if (minute >= 0 && minute < 60)
return new DateTime(year, monthofyear, dayofmonth, hour, minute, 0);
return DateTime.MinValue;
}
You can modify this to handle different string lengths for 14, 12, 8 chars and so on. Verify input before calling it.
精彩评论