Search code examples
c#mysqldatelocalization

How to get date in C#, without localisation


My C# application have to read some date from MySQL database. Problem I have is that format of date depends on system localisation settings.

My question is if is possible that I always get date in formats yyyy-MM-dd hh:mm:ss, and yyyy-MM-dd, no matter of localisation settings.

Thank you in advance!


Solution

  • If you are storing the dates as true date or datetime values, your application will get the raw binary data back, and it will not be subject to localization until you create a string representation of the date values. My guess is that you are looking at the values in the debugger or using Console.WriteLine(theValue);, which will use the current locale. Always include the desired format and/or the desired culture when converting non-string values to strings.

    If you are storing the dates as strings, you will always have to know exactly what format went into the database.

    Assuming the dates are stored as date or datetime: just handle the values as they are, and don't convert them to strings until you need to show them to a user:

    DateTime theValue = theReader.GetDateTime(fieldOrdinal);
    var theValueAsText = theValue.ToString(CultureInfo.InvariantCulture);
    var specificTextRepr = theValue.ToString("yyyy-MM-dd HH:mm:ss");
    

    The theValueAsText variable will be a string representation that is not tied to a specific culture. The specificTextRepr will be your specific text representation.