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.?
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.?
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
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
hh
format specifier will return 12 hour based hours.tt
format specifier will return the AM/PM designator.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
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();