Formatting a datetime string in the YYYYMMDD format

  • 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?

    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.

    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

  • Yes there is: Date Formatting

    var dateString = DateTime.Now.ToString("yyyyMMdd");

License under CC-BY-SA with attribution

Content dated before 7/24/2021 11:53 AM