Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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?

share|improve this question
4  
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. –  svick Mar 22 '12 at 18:50

2 Answers 2

up vote 16 down vote accepted

Yes there is: Date Formatting

var dateString = DateTime.Now.ToString("yyyyMMdd");
share|improve this answer

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.

share|improve this answer
    
That's proper coding, thanks! –  Eric Herlitz Apr 5 '12 at 12:21

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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