Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format the time portion of a DateTime with leading space for single-digit hours

I'm working on a project where I need to format a string with a bunch of stuff but the pertinent part is the first part - the time of a tour:

Given

DateTime start = Convert.ToDateTime(myClass.StartDateTime);

How do I output it with string.Format to show either 10:00 or < space >3:00?

I know I can use a format string like:

string  text = string.Format("{0:hh:mm tt}",_start);

but that gives me a leading zero (03:00 PM) that I don't want for single digit hours.

Is there something I can add into the format string to do this or do I have to manually substitute a space for a leading zero? (I suspect this is the case but wanted to ask so I can learn how if there is a format method.)

like image 377
Deverill Avatar asked Jul 11 '13 20:07

Deverill


People also ask

What is the format of DateTime?

For example, the "d" standard format string indicates that a date and time value is to be displayed using a short date pattern. For the invariant culture, this pattern is "MM/dd/yyyy". For the fr-FR culture, it is "dd/MM/yyyy". For the ja-JP culture, it is "yyyy/MM/dd".

What is %f in date format?

The %f and %m can be used for one or two digit months. When a format specifier contains %f, single digit months are displayed as a single digit. When using %m, single digit months are displayed with a leading zero. For example, %f %e %Y will display the date 2 5 2018 with a single digit for the month.

What does TT stand for in time format?

Terrestrial Time (TT) is a modern astronomical time standard defined by the International Astronomical Union, primarily for time-measurements of astronomical observations made from the surface of Earth.


2 Answers

string  _text = string.Format("{0:h:mm tt}",_start).PadLeft(8, ' ');

should do it.

The single "h" in the Time Format String will make it so that the zero doesn't show if it is a single digit hour,l and the PadLeft function will ensure that it is the proper width.

like image 165
David Avatar answered Oct 11 '22 18:10

David


You can have a conditional check in the ToString overload.

string _text = _start.ToString((_start.Hour > 9) ? "hh:mm tt" : " h:mm tt");
like image 6
keyboardP Avatar answered Oct 11 '22 18:10

keyboardP