That’s Another Way to Go About It

I generally don’t like to showcase other’s inelegant code, but this couldn’t be more timely given yesterday’s Twitter created_at parsing tip. There’s always more than one way to do something, I guess.


       private static DateTime ParseDateString(string DateString)
{
Regex re = new Regex(@"(?<DayName>[^ ]+) (?<MonthName>[^ ]+) (?<Day>[^ ]{1,2}) ↵
(?<Hour>[0-9]{1,2}): (?<Minute>[0-9]{1,2}): (?<Second>[0-9]{1,2}) ↵
(?<TimeZone>[+-][0-9]{4}) (?<Year>[0-9]{4})");
Match CreatedAt = re.Match(DateString);
DateTime parsedDate = DateTime.Parse(
string.Format(
"{0} {1} {2} {3}:{4}:{5}",
CreatedAt.Groups["MonthName"].Value,
CreatedAt.Groups["Day"].Value,
CreatedAt.Groups["Year"].Value,
CreatedAt.Groups["Hour"].Value,
CreatedAt.Groups["Minute"].Value,
CreatedAt.Groups["Second"].Value));

return parsedDate;
}

For me, the lesson here is to know your libraries and always assume that someone else has done it better than you already. It then becomes a quest to find that better solution to the problem.

Advertisements

%d bloggers like this: