4
\$\begingroup\$

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:

string date = string.Concat(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);

Is there a better practice?

\$\endgroup\$
  • 5
    \$\begingroup\$ Be careful when calling DateTime.Now several times like this. For example, if DateTime.Now.Month is called just before the midnight of 31 January and DateTime.Now.Day after the midnight, you will get the date like 20120101. It's unlikely, but certainly possible. \$\endgroup\$ – svick Mar 22 '12 at 18:50
  • 1
    \$\begingroup\$ This is already 'answered', but the main difference between their method and yours is how 1 digit months and dates will be handled. Yours would print 201911 for 1st Jan 2019, whereas the others will print 20190101 \$\endgroup\$ – Matthew Steeples Nov 29 at 20:26
18
\$\begingroup\$

Yes there is: Date Formatting

var dateString = DateTime.Now.ToString("yyyyMMdd");
\$\endgroup\$
5
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.