Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Date format not showing local format

On my local machine, my Thread.CurrentThread.CurrentCulture returns the correct local culture (en-GB). The date format is set to yyyy-MM-dd.

In code, when I run:

value.ToShortDateString()

it returns "6/2/2010" (m/d/yyyy).

How can I get it to display according the the local culture? I do not want to hard code a format as the app will be deployed in different countries, so it should work according to the local pc setup. I've also tested on a en-US and it displays the same.

The value of my 'value' variable is:

{6/2/2010 12:00:00 AM}
    Date: {6/2/2010 12:00:00 AM}
    Day: 2
    DayOfWeek: Wednesday
    DayOfYear: 153
    Hour: 0
    Kind: Unspecified
    Millisecond: 0
    Minute: 0
    Month: 6
    Second: 0
    Ticks: 634110336000000000
    TimeOfDay: {00:00:00}
    Year: 2010
like image 731
Cameron Castillo Avatar asked Dec 02 '25 06:12

Cameron Castillo


1 Answers

Simply call ToString() rather than ToShortDateString() and specify your date format:

    DateTimeFormatInfo formatInfo = CultureInfo.CurrentUICulture.DateTimeFormat;
    var value = DateTime.Now.ToString(formatInfo);

Though ToShortDateString() should be culture-sensitive as per the documentation:

The value of the current DateTime object is formatted using the pattern defined by the DateTimeFormatInfo.ShortDatePattern property associated with the current thread culture. The return value is identical to the value returned by specifying the "d" standard DateTime format string with the ToString(String) method.

However, it could return the wrong format if the CurrentCulture and the CurrentUICulture differ. To be safe, I've made it use the CurrentUICulture in the code sample, as it is based on the user's UI culture settings - e.g. UK language pack on US system etc. and should be correct.

like image 143
aevitas Avatar answered Dec 03 '25 20:12

aevitas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!