0

I expect ToString("MM/dd/yyyy") to ignore the system settings and always output the format as defined. The below test passes if I set my Windows 10 date string set to the 08/27/2020 format but fails if I set it to 2020-08-27 format with the below error.

Am I missing something?

[Test]
public void TestDate() {
Assert.AreEqual("08/08/2020", (new DateTime(2020, 8, 8)).ToString("MM/dd/yyyy"));
}

Results

String lengths are both 10. Strings differ at index 2.
Expected: "08/08/2020"
But was:  "08-08-2020"
John Hughes
  • 367
  • 1
  • 3
  • 20
  • If you want ToString to ignore the system settings you need to provide a culture yourself, e.g. `ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);`. – ckuri Aug 29 '20 at 08:29

1 Answers1

0

Ok, while typing this, I was shown this work around. I still this this is a problem.

[Test]
public void TestDate() {
    Assert.AreEqual("08/08/2020", (new DateTime(2020, 8, 8)).ToString(@"MM\/dd\/yyyy"));
}

Per comments below "MM'/'dd'/'yyyy" works too.

John Hughes
  • 367
  • 1
  • 3
  • 20
  • 2
    It's not a workaround. This is by design so it's an expected course of action (there are multiple ways to escape special characters in format strings). The `/` character is a placeholder for the culture-specific date separator and is discussed in the [documentation](https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings#dateSeparator). – madreflection Aug 27 '20 at 19:13
  • The '/' character is substituted by DateTimeFormatInfo.CurrentInfo.DateSeparator. This is by design, you could escape it, but I do not understand what exactly do you want to achieve by this test. – Konstantin Borisov Aug 27 '20 at 19:18
  • @KonstantinBorisov I am send date in query to another server, I was using the format string to format the date. When I ran the unit tests on my computer, they all failed because of invalid dates. I investigated and found that on my system the dates were formatted one way and on the other computer they were formatted another way. I wrote this simple test so I could check as I changed the system date format on my system. The test serves no other useful purpose then to demo the problem. – John Hughes Aug 27 '20 at 19:48
  • @JohnHughes, then I would say your test operates exactly as it should. Since you need to ensure that your system date format has slashes as the delimeter, it fails when you have dashes. You might want to update the separator for your thread (but again looks like your test works as expected): https://stackoverflow.com/questions/56899198/instance-is-read-only-exception-while-changing-culture-in-asp-net – Konstantin Borisov Aug 27 '20 at 20:05