how to convert 24-hour format TimeSpan to 12-hour format TimeSpan?
TimeSpan
represents a time interval not a time of day. The DateTime
structure is more likely what you're looking for.
(Summing up my scattered comments in a single answer.)
First you need to understand that TimeSpan
represents a time interval. This time interval is internally represented as a count of ticks an not the string 14:00:00
nor the string 2:00 PM
. Only when you convert the TimeSpan
to a string does it make sense to talk about the two different string representations. Switching from one representation to another does not alter or convert the tick count stored in the TimeSpan
.
Writing time as 2:00 PM
instead of 14:00:00
is about date/time formatting and culture. This is all handled by the DateTime
class.
However, even though TimeSpan
represents a time interval it is quite suitable for representing the time of day (DateTime.TimeOfDay
returns a TimeSpan
). So it is not unreasonable to use it for that purpose.
To perform the formatting described you need to either rely on the formatting logic of DateTime
or simply create your own formatting code.
Using
DateTime
:var dateTime = new DateTime(timeSpan.Ticks); // Date part is 01-01-0001 var formattedTime = dateTime.ToString("h:mm tt", CultureInfo.InvariantCulture);
The format specifiers using in
ToString
are documented on the Custom Date and Time Format Strings page on MSDN. It is important to specify aCultureInfo
that uses the desired AM/PM designator. Otherwise thett
format specifier may be replaced by the empty string.Using custom formatting:
var hours = timeSpan.Hours; var minutes = timeSpan.Minutes; var amPmDesignator = "AM"; if (hours == 0) hours = 12; else if (hours == 12) amPmDesignator = "PM"; else if (hours > 12) { hours -= 12; amPmDesignator = "PM"; } var formattedTime = String.Format("{0}:{1:00} {2}", hours, minutes, amPmDesignator);
Admittedly this solution is quite a bit more complex than the first method.
TimeSpan
represents a time interval (a difference between times),
not a date or a time, so it makes little sense to define it in 24 or 12h format. I assume that you actually want a DateTime
.
For example 2 PM of today:
TimeSpan ts = TimeSpan.FromHours(14);
DateTime dt = DateTime.Today.Add(ts);
Then you can format that date as you want:
String formatted = String.Format("{0:d/M/yyyy hh:mm:ss}", dt); // "12.4.1012 02:00:00" - german (de-DE)
http://msdn.microsoft.com/en-us/library/az4se3k1%28v=vs.100%29.aspx
You need to convert the TimeSpan to a DateTime object first, then use whatever DateTime format you need:
var t = DateTime.Now.TimeOfDay;
Console.WriteLine(new DateTime(t.Ticks).ToString("hh:mm:ss tt"));
ToShortTimeString()
would also work, but it's regional-settings dependent so it would not display correctly (or correctly, depending on how you see it) on non-US systems.