Format string time in short time format

I have a collection of data in my database, time and description, select String as the data type of my time, my question is how can I format time data in this format "HH: MM AM / PM"

The time is "4:45 PM", I want to format it in this format "04:45 PM" in C #, but I do not know how this can be formatted.

here is my code:

var str = touritinerary.Model.Time; //"4:45 PM"
var timePattern = "h:mm";
DateTime finalizeTime;
if (DateTime.TryParseExact(str, timePattern, null, DateTimeStyles.None, out finalizeTime))
{
  Console.WriteLine("Time: {1:hh:mm }", finalizeTime);
}

I want 16:45 formatted at 16:45

+3
source share
3 answers

You are close.

  • Use 0instead 1, as it finalizeTimeis the first (and only) argument WriteLine.
  • Enable ttto display PM.

Try the following:

Console.WriteLine("Time: {0:hh:mm tt }", finalizeTime);

Conclusion:

Time: 04:45 PM

+5

You will find this page incredibly useful, it has all the DateTime formatting information you need from MSDN.

Console.WriteLine("Time: {0: hh:mm tt}", finalizeTime);
-2
source

All Articles