patterncsharpMinor
optimizing conversion between string and date
Viewed 0 times
conversiondatebetweenoptimizingandstring
Problem
I was wondering if there was a more efficient way of taking strings that represent dates with the pattern being
The spaces are either ' ' or '\0' (the input I am given is not very clean)
This is what I have so far, which works for all cases.
mmddyy or mmd yy or m d yy and converting them into a DateTime object?111110 would be 11 11 10111 10 would be 11 1 101 1 10 would be 1 1 10The spaces are either ' ' or '\0' (the input I am given is not very clean)
This is what I have so far, which works for all cases.
//Converts a given input string into a valid date
private DateTime convertToDateFromString(string dateString)
{
int length = dateString.Length;
int month = 1;
int day = 1;
int year = 1;
bool gotMonth = false;
bool gotDay = false;
bool gotYear = false;
char c = ' ';
char peek = ' ';
string buffer = "";
DateTime bufferDate;
int count = 0;
try
{
for (int i = 0; i = 80 && year = 0 && year <= 79)
year += 2000;
}
}
}
bufferDate = new DateTime(year, month, day);
}
catch (System.Exception ex)
{
bufferDate = new DateTime(1, 1, 1);
}
return bufferDate;
}Solution
Here's a one-liner for you:
With more than one line:
private DateTime convertToDateFromString(string dateString)
{
DateTime bufferDate;
return DateTime.TryParseExact(
dateString,
new[] { "MMddyy", "MMd yy", "M d yy" },
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out bufferDate)
? bufferDate
: new DateTime(1, 1, 1);
}With more than one line:
private DateTime convertToDateFromString(string dateString)
{
var allowedFormats = new[] { "MMddyy", "MMd yy", "M d yy" };
DateTime parsedDate;
var couldParse = DateTime.TryParseExact(
dateString,
allowedFormats,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out parsedDate);
if (couldParse)
{
return parsedDate;
}
return new DateTime(1, 1, 1); // or throw an exception
}Code Snippets
private DateTime convertToDateFromString(string dateString)
{
DateTime bufferDate;
return DateTime.TryParseExact(
dateString,
new[] { "MMddyy", "MMd yy", "M d yy" },
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out bufferDate)
? bufferDate
: new DateTime(1, 1, 1);
}private DateTime convertToDateFromString(string dateString)
{
var allowedFormats = new[] { "MMddyy", "MMd yy", "M d yy" };
DateTime parsedDate;
var couldParse = DateTime.TryParseExact(
dateString,
allowedFormats,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out parsedDate);
if (couldParse)
{
return parsedDate;
}
return new DateTime(1, 1, 1); // or throw an exception
}Context
StackExchange Code Review Q#5952, answer score: 5
Revisions (0)
No revisions yet.