Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert timespan to pm or am time?

Tags:

c#

asp.net

I'm storing user time in UTC time and when I show it I need to convert it to am pm time.

Here is example in database I have 17:00:00 convert to 5:00 pm

Here is the code what I came up so far but it's not working

var time = DateTime.ParseExact(object.Time.ToString(), "HHmm", CultureInfo.CurrentCulture).ToString("hh:mm tt");
like image 653
Andrew Venture Avatar asked Jul 17 '11 13:07

Andrew Venture


2 Answers

I just needed to display static html with my TimeSpan. So in my view I used,

DateTime.Today.Add(StartTime).ToString("%h:mm tt")

"StartTime" is my TimeSpan, it converts it to a DateTime and then displays it. My time now displays as "3:00 PM" instead of "15:00". The "%h" eliminates a leading zero for time that is between 1-9.

like image 134
Morgan Kenyon Avatar answered Oct 19 '22 13:10

Morgan Kenyon


TimeSpan is a duration "17 hours", not a time. Maybe add this to a date (only) and use the existing datetime formatting options? (although watch for daylight savings)

i.e.

string s = DateTime.Today.Add(duration).ToString(specifier);
like image 34
Marc Gravell Avatar answered Oct 19 '22 12:10

Marc Gravell