Alex Rivera | Logout

how to convert 24-hour format TimeSpan to 12-hour format TimeSpan?

Asked 2012-04-12T12:18:18.507
17

I have TimeSpan data represented as 24-hour format, such as 14:00:00, I wanna convert it to 12-hour format, 2:00 PM, I googled and found something related in stackoverflow and msdn, but didn't solve this problem, can anyone help me? Thanks in advance.

Update Seems that it's possible to convert 24-hour format TimeSpan to String, but impossible to convert the string to 12-hour format TimeSpan :(

But I still got SO MANY good answers, thanks!

c#
Edit
Report

1 Answer

8

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

answered 2012-04-12T12:25:20.523

Your Answer