Last month after I installed Windows 10 on my computer at work, some of the UI tests started to fail because the date string on the UI did not match the expected date string. i.e.
Date string on UI: 15-01-2016
Expected date string: 15/01/2016
The interesting thing was that in the code where it the date is displayed, it was ToString(“dd/mm/yyyy”).
var today = DateTime.Today.ToString("dd/mm/yyyy");
The date format setting on my computer was dd-mm-yyyy. I was quite surprised that even though the specific format was given, the computer date format was used instead.
After some quick research, “/” is a date separator which is used to differentiate days, months and year. This will use the localised date seperator from the current culture. This explains why the date string was in the format dd-mm-yyyy as that is the current setting on my computer.
There are 2 ways to get it to return in the format dd/mm/yyyy.
- Use CultureInfo.InvariantCulture.
var today = DateTime.Today.ToString("dd/mm/yyyy", CultureInfo.InvariantCulture);
- Use format string dd’/’mm’/’yyyy produces a result string in which “/” is always used as the date separator
var today = DateTime.Today.ToString("dd'/'MM'/'yyyy")