Search code examples
c#.netdatetimelocalizationdate-formatting

Inconsistent Date Format when writing a CSV


I'm facing a very strange issue. I'm writing to a CSV file like this:

sw.WriteLine($"{posting.publishedOn},{posting.ExpirationDate}");

Posting Date is a DateTime object and Expiration Date is a DateTime? object.

However, when I run this on my production server in Germany, it's very inconsistent as to which date format it prints out. Sometimes I will have dates formatted like this (European style):

Posting Date,Expiration Date
06.08.2018 11:49,08.07.2018 11:49

And sometimes I will have dates formatted like this (U. S. style):

Posting Date,Expiration Date
8/15/2018 7:56:12 AM,10/14/2018 7:56:12 AM

Posting Date and Expiration Date are completely separate .NET Objects, but each line will be consistent - i.e. if one column is in European format, the other one will be as well.

I tried setting the culture like this:

CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

but it didn't seem to make a difference.

This happens when I run the console application on my server in Germany.

What could be causing this? Is there a way to fix it without having to explicitly call ToString with a format every time I write a date?


Solution

  • Are you absolutely sure that the serialization is always happening in the same thread whose culture is being set?

    Because if not, that may be the issue.

    Just to debug it, please set the current thread culture immediately before the serialization code and check if the issue still happens, i.e.

    Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
    
    sw.WriteLine($"{posting.publishedOn},{posting.ExpirationDate}");