U.S. and U.S. show times

Update

I want to show the date time value in 24 hour format for the UK or USA depending on the current culture, using the general method.

The code below (NOT a valid code, just for the question):

    var dt = new DateTime(2011, 4, 15, 17, 50, 40);        
    Console.WriteLine(dt.ToString("d", new CultureInfo("en-us")) + " "
        + dt.ToString("H:mm:ss", new CultureInfo("en-us")));
    Console.WriteLine(dt.ToString("G", new CultureInfo("en-gb")));

The result is below:

4 /15/2011 17:50:40
15/04/2011 17:50:40

It is displayed normally.

Is there a better way to display time without using "H: mm: ss". Please note that The G for USA displays PM, which I don't want.

In month 4 for the US, not 04, there is a way to show it in 04 . .

Update

Below I want, ideally, using the general method:

US: 04/15/2011 17:50:40
United Kingdom: 04/15/2011 17:50:40

+3
source
3

.

DateTime dt = new DateTime(2011, 4, 15, 17, 50, 40);        
Console.WriteLine(dt.ToString("MM/dd/yyy H:mm:ss"));// US format
Console.WriteLine(dt.ToString("dd/MM/yyy H:mm:ss"));// UK format

MSDN

+2

, ,

DateTime dt = DateTime.Now;
Console.WriteLine(dt.ToString(@"MM/dd/yy HH\:mm\:ss"));
Console.ReadLine();
// Displays 05/20/12 17:08:37

http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

+1

You can do something similar for US:

CultureInfo ci = new CultureInfo("en-us", true);
ci.DateTimeFormat.ShortDatePattern = "MM/dd/yyyy";
ci.DateTimeFormat.LongTimePattern = "HH:mm:ss";
ci.DateTimeFormat.AMDesignator = "";
ci.DateTimeFormat.PMDesignator = "";

Now you can set the current thread culture as follows:

Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;

And display the following date:

Console.WriteLine(dt.ToString("G"));

Or you can pass the culture as a parameter to the ToString method as follows:

Console.WriteLine(dt.ToString("G", ci));

If you prefer the second method, you can wrap the code above in a static method so that you can call it like this:

Console.WriteLine(dt.ToString("G", Cultures.EnUs));
0
source

All Articles