In search of a simpler approach - and something easier on the eyes
How would you re-write the following, so it's a bit easier on the eyes?
Func<DateTime, String> formatter = null;
formatter = new Func<DateTime, String>(d =>
{
var r = "开发者_如何学编程";
foreach (var i in new[] { d.Day, d.Month, d.Year })
{
if (i < 10) r += "0";
r += i.ToString();
}
return r;
});
I'd rewrite it as:
Func<DateTime, String> formatter = d => d.ToString("ddMMyyyy",
CultureInfo.InvariantCulture);
Only difference here is that for dates before 1000AD, this will pad to 4 digits instead of 2...
EDIT: As noted in comments, this doesn't replicate the bug in the original code - it would format (say) a month of 5 as "055". The simplest way to fix this in the original code would be:
if (i < 10) r += "0";
r += i;
(But I'd prefer my code anyway :)
I like Jon Skeets answer best, but I'd like to offer an alternative:
Func<DateTime, String> formatter = d => string.Format(
"{0:00}{1:00}{2:00}",
d.Day, d.Month, d.Year);
I always check this site for string formatting: http://blog.stevex.net/string-formatting-in-csharp/
Any reason not to exchange the entire formatter code with a ToString("ddMMyyyy")
?
Func<DateTime, String> formatter = d => d.ToString("ddMMyyyy");
精彩评论