Another option would be to create an extension methods like:
public static class DateTimeExtensions
{
public static string ToYMD(this DateTime theDate)
{
return theDate.ToString("yyyyMMdd");
}
public static string ToYMD(this DateTime? theDate)
{
return theDate.HasValue ? theDate.Value.ToYMD() : string.Empty;
}
}
You would use it like:
var dateString = DateTime.Now.ToYMD();
The extension implemented also works for Nullable DateTime values.
If you are doing a lot of work with these 'yyyyMMdd' formatted DateTime values, the extension method has the benefit of less typing.
DateTime.Now
several times like this. For example, ifDateTime.Now.Month
is called just before the midnight of 31 January andDateTime.Now.Day
after the midnight, you will get the date like20120101
. It's unlikely, but certainly possible. \$\endgroup\$ – svick Mar 22 '12 at 18:50