snippetcsharpMinor
Formatting a datetime string in the YYYYMMDD format
Viewed 0 times
formattingformattheyyyymmddstringdatetime
Problem
I'm working with some strange APIs that requires the dates to be sent in the YYYYMMDD format.
I was thinking of doing something like this:
Is there a better practice?
I was thinking of doing something like this:
string date = string.Concat(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);Is there a better practice?
Solution
Another option would be to create an extension methods like:
You would use it like:
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.
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.
Code Snippets
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;
}
}var dateString = DateTime.Now.ToYMD();Context
StackExchange Code Review Q#10250, answer score: 5
Revisions (0)
No revisions yet.