Amit Kumar Amit Kumar - 3 months ago 36
C# Question

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

I have a value stored in variable of type

System.TimeSpan
as follows.

System.TimeSpan storedTime = 03:00:00;


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

String displayValue = "03:00 AM";


And if
storedTime
variable has the value of

storedTime = 16:00:00;


then it should be converted to:

String displayValue = "04:00 PM";

Answer

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"
Comments