I was greeted with a nasty bug today. The task is pretty trivial, all I needed to do is to convert the DateTime object to string in \"yyyymmdd\" format
String.Format("{0:0000}{1:00}{2:00}", dateTime.Year, dateTime.Month, dateTime.Day);
You could use this instead, I prefer the terse format though. Instead of 00 you can also use MM for specific month formatting (like in DateTime.ToString()
).
return dateTime.Year.ToString() + dateTime.Month + dateTime.Day;
You don't need to keep adding empty strings, string+number returns string already and addition is interpreted from left to right.
Do note that that line doesn't return what you think it does, what you really want is:
return dateTime.Year.ToString("0000") + dateTime.Month.ToString("00")
+ dateTime.Day.ToString("00");
If that format string bugs you that much, at least make sure it is in one place. Encapsulate it e.g. in an extension method:
public string ToMyAppsPrefferedFormat(this DateTime date) {
return date.ToString("ddMMyyyy");
}
Then you can say date.ToMyAppsPrefferedFormat()
See here: .NET Custom Date and Time Format Strings