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.)
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".
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.
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.
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.
You can have a conditional check in the ToString
overload.
string _text = _start.ToString((_start.Hour > 9) ? "hh:mm tt" : " h:mm tt");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With