开发者

datetime in c# how to change the default returned value to 24hrs?

开发者 https://www.devze.com 2023-01-13 00:52 出处:网络
yes what returned can be formatted using HH to display value in 24hrs, but开发者_运维百科 is there a way to make this the default returned value.?Instead of playing with Cultures, make an extension m

yes what returned can be formatted using HH to display value in 24hrs,

but开发者_运维百科 is there a way to make this the default returned value.?


Instead of playing with Cultures, make an extension method:

public static class Extensions
{
    public static string To24HourTime(this DateTime dateTime)
    {
        return dateTime.ToString("HH:mm:ss");
    }
}

You can use the method as follows then:

DateTime.Now.To24HourTime();


The internal representation is not relevant. If you are returning a DateTime, it will be a DateTime.

If you want to format the DateTime for display, then you need to use a format string to display it in whatever format you want.

See MSDN for the different custom datatime format strings.

DateTime date1; 
date1 = new DateTime(2008, 1, 1, 18, 9, 1);
Console.WriteLine(date1.ToString("hh:mm:ss tt", 
                  CultureInfo.InvariantCulture));
// Displays 06:09:01 PM  

Console.WriteLine(date1.ToString("HH:mm:ss", 
                  CultureInfo.InvariantCulture));
// Displays 18:09:01       
  • The hh format specifier will return 12 hour based hours.
  • The tt format specifier will return the AM/PM designator.
  • The HH format specifier will return 24 hour based hours.

You can, as others have pointed out, change the thread cultures to a culture that uses 24 hours by default, but this will also effect formatting of numbers (decimal and thousands separators, for instance).


Change the CultureInfo on the current thread to a Culture that has 24hrs as default.

//In Sweden we use 24hrs format.
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("sv-se");

Edit: You could also just change the time format for the current culture info.

Thread.CurrentThread.CurrentCulture.DateTimeFormat.LongTimePattern = "HH:mm:ss";
Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortTimePattern = "HH:mm";

//DateTime.ToString() will output something like (en-us culture) 8/21/2010 10:11:37


This depends on which culture your program is running on. Check the System.Threading.Thread.CurrentThread.CurrentCulture and CurrentUICulture properties and set these accordingly.

The CultureInfo type, among other tings, tells how numbers and dates are formatted. The DateTimeFormat property is what you are interested in. If you need a specialized culture you can create one and set its DateTimeFormat to whatever you need, and then assign it to the CurrentCulture property.

Most probably you just want to select a pre-defined culture. Read more here: http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.aspx

0

精彩评论

暂无评论...
验证码 换一张
取 消