How to convert timespan to pm or am time?

2020-02-28 07:28发布

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");

标签: c# asp.net
5条回答
贪生不怕死
2楼-- · 2020-02-28 07:40

Based on your comment, first convert the TimeSpan to a DateTime:

var dtUtc = DateTime.Now.ToUniversalTime();
dtUtc.AddHours(timeSpanObject.Hours);
dtUtc.AddMinutes(timeSpanObject.Minutes);

Once it's a DateTime, you can convert it from UTC to localtime:

var dtLocal = dtUtc.ToLocalTime();

Only when you display it would you include AM/PM, like:

dtLocal.ToString("h:mm tt");
查看更多
家丑人穷心不美
3楼-- · 2020-02-28 07:43
var time = DateTime.ParseExact("17:00", "HH:mm", null).ToString("hh:mm tt");

returns 05:00 PM

DateTime.ParseExact is returning DateTime

Edited:

Include CultureInfo

var time = DateTime.ParseExact("17:00", "HH:mm", null).ToString("hh:mm tt", CultureInfo.GetCultureInfo("en-US"));
查看更多
看我几分像从前
4楼-- · 2020-02-28 07:46

Don't forget to specify appropriate culture, e.g.: CultureInfo.InvariantCulture.

var time = DateTime.Now.ToString("h:mm tt", CultureInfo.InvariantCulture);

See also: Custom Date and Time Format Strings

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2020-02-28 07:47

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.

查看更多
我想做一个坏孩纸
6楼-- · 2020-02-28 07:52

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);
查看更多
登录 后发表回答