DateTimes and Cultural Differences in C#

Wednesday, April 23, 2014

The most baffling bugs are the ones that only appear on a remote server and are impossible to reproduce locally. We had one of these recently on a page that retrieved data based on date periods. Locally, the data came back as expected; on our test server, we got nothing. It took us a little while to realise that the problem was date time cultures.

We had a method that expected date times from the browser:

public Metric GetData(DateTime startDate, DateTime endDate){
// retrieve data and return

The datepicker in the browser was using a ‘dd/mm/yyyy’ format and passing this to the server method. But whereas our local machines expected UK style dates and so parsed this correctly, the test server expects US style dates so was parsing this as ‘mm-dd-yyyy’.

We wanted our method to work correctly on all servers, without having to know the culture. Here’s the solution:

1. Change the method to expect strings instead of DateTimes
2. Convert each string to a DateTime inside the method, using the C# method DateTime.ParseExact(). As long as you know the format the browser is using, you can get the correct date back.

public Metric GetData(string startDate, string endDate){
var dateFrom = DateTime.ParseExact(startDate, "dd/MM/yyyy", null);
var dateTo = DateTime.ParseExact(endDate, "dd/MM/yyyy", null);

// retrieve data as before

Well, it seems simple now but took me a while to actually hit on this as the solution! So hopefully this will
help anyone else having similar issues.

Leave a Reply

Your email address will not be published. Required fields are marked *