DateTime.ToString() gotcha
Atruna: Esmu nolēmis izmēģināt rakstīšanu divās valodās un kādu laiku publicēt ierakstus gan latviski, gan angliski. Šis ieraksts ir anglisks tulkojums rakstam “DateTime.ToString() nianse”.
Disclaimer: I have decided to try dual language blogging and for some time post in both Latvian and English. This is English translation of “DateTime.ToString() nianse”.
Recently I got bitten by an interesting gotcha in DateTime.ToString() templates. It turned out that the slash character “/” specifies the date separator which is replaced with localized value from current or specified culture.
To demonstrate we can use this test:
- [TestMethod]
- public void FailingTest()
- {
- var date = new DateTime(2011, 11, 11);
- var expected = "2011/11/11";
- var actual = date.ToString("yyyy/MM/dd");
- Assert.AreEqual(expected, actual);
- }
If your computers regional settings have set date separator, other than “/”, test should fail. Otherwise you can specify culture explicitly to reproduce same behaviour.
What to do if you need date separated with slashes? It’s simple, you just need to escape the slash with an apostrophes.
Following test will pass:
- [TestMethod]
- public void SucessfulTest()
- {
- var date = new DateTime(2011, 11, 11);
- var expected = "2011/11/11";
- var actual = date.ToString("yyyy'/'MM'/'dd");
- Assert.AreEqual(expected, actual);
- }
For “works on my machine” proof, there is screenshot:
