Amit Kumar Amit Kumar - 1 year ago 139
C# Question

Convert time span value to format "hh:mm Am/Pm" using C#

I have a value stored in variable of type

as follows.

System.TimeSpan storedTime = 03:00:00;

Can I re-store it in another variable of type
as follows?

String displayValue = "03:00 AM";

And if
variable has the value of

storedTime = 16:00:00;

then it should be converted to:

String displayValue = "04:00 PM";

Answer Source

You can do this by adding your timespan to the date.

TimeSpan timespan = new TimeSpan(03,00,00);
DateTime time = DateTime.Today.Add(timespan);
string displayTime = time.ToString("hh:mm tt"); // It will give "03:00 AM"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download