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

前端 未结 11 1336
一生所求
一生所求 2020-11-28 07:22

I have a value stored in variable of type System.TimeSpan as follows.

System.TimeSpan storedTime = 03:00:00;

Can I re-store it

11条回答
  •  攒了一身酷
    2020-11-28 07:38

    You cannot add AM / PM to a TimeSpan. You'll anyway have to associate the TimaSpan value with DateTime if you want to display the time in 12-hour clock format.

    TimeSpan is not intended to use with a 12-hour clock format, because we are talking about a time interval here.

    As it says in the documentation;

    A TimeSpan object represents a time interval (duration of time or elapsed time) that is measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. The TimeSpan structure can also be used to represent the time of day, but only if the time is unrelated to a particular date. Otherwise, the DateTime or DateTimeOffset structure should be used instead.

    Also Microsoft Docs describes as follows;

    A TimeSpan value can be represented as [-]d.hh:mm:ss.ff, where the optional minus sign indicates a negative time interval, the d component is days, hh is hours as measured on a 24-hour clock, mm is minutes, ss is seconds, and ff is fractions of a second.

    So in this case, you can display using AM/PM as follows.

    TimeSpan storedTime = new TimeSpan(03,00,00);
    string displayValue = new DateTime().Add(storedTime).ToString("hh:mm tt");
    


    Side note :
    Also should note that the TimeOfDay property of DateTime is a TimeSpan, where it represents

    a time interval that represents the fraction of the day that has elapsed since midnight.

提交回复
热议问题