Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# format time "On The Hour"

I need to format the time from a DateTime object as a string. The catch is, if the time is "on the hour" as in 12:00AM, 8:00PM, I need to trim the zeros and display 12AM or 8PM.

Is there an easy way to do this that I am missing?

like image 419
stephen776 Avatar asked Nov 28 '22 18:11

stephen776


2 Answers

Unless I'm missing something, you can do this:

DateTime date = DateTime.Now;
if (date.Minute == 0) {
   return date.ToString("Htt");
} else {
   return date.ToString("H:mmtt");
}

Obviously with the extra formatting wrapped around this. But that's the core of it.

like image 23
Alastair Avatar answered Dec 10 '22 06:12

Alastair


You'll have to do the check yourself:

dateTime.ToString(dateTime.Minute == 0 ? "Htt" : "H:mmtt");
like image 136
Adam Robinson Avatar answered Dec 10 '22 05:12

Adam Robinson