Search code examples
c#datetimenamed-pipes

DateTime.Parse sometimes throws FormatException over Pipes


I am trying to send a DateTime from one process to another. My first thought was to send the DateTime as a string and parse the string back to DateTime onces received. Unfortunately on some machines I get a FormatException even though the string looks good e.g. "31.10.2019 12:00:00" (no hidden characters).

The code looks like this, I will omit the communication since the string is correctly transferred.

var datetimeAsString = SomeDateTime.ToString();      // "31.10.2019 12:00:00"
Pipe.Send(StringToBytes(datetimeAsString));
// Data gets send
var datetimeAsString = BytesToString(receivedBytes); // "31.10.2019 12:00:00"
var datetime = DateTime.Parse(datetimeAsString);

Please note that it works on some machines.


Solution

  • TL;DR

    When trying to send DateTime between different systems, do NOT convert it to a string using ToString() without parameter use DateTime.ToBinary and DateTime.FromBinary instead OR if you want a string specify a culture e.g.

    var datetimeAsString = thisDate.ToString(new CultureInfo("en-us"));
    DateTime.Parse(datetimeAsString, new CultureInfo("en-us"));
    

    PS: I think this not only applies to situations where you want to exchange data but also to other situations and therefore should be seen as a general advice.

    --

    The problem was that the software that sent the DateTime converted the DateTime.ToString() to a German format, even though the software was in English. The receiving software was sometimes in German and sometime in English. The software with the German language was able to use DateTime.Parse on the German string, the other systems weren't.

    The solution was to not convert the DateTime to a string but to a long using the DateTime.ToBinary method. I think is would also been possible to solve it with CultureInfo.InvariantCulture, but we thought long was much cleaner.