How to convert a 24 hour time to 12 hour in VB.net as hh:mm AM/PM

eastboundr picture eastboundr · Jun 12, 2012 · Viewed 69.9k times · Source

So let's say I have 1400, I want to convert it into 2:00PM

I tried the following:

Dim convertedTime As String = DateTime.ParseExact(theTime,"HHmm", Nothing)

And it would give me this:

6/12/2012 02:00:00 PM

I do not want the date part, neither do I need the seconds. All I need is 2:00PM

How could I achieve this? Thanks!

Answer

Guffa picture Guffa · Jun 12, 2012

The ParseExact method returns a DateTime value, not a string. If you assign it to a string variable you will be converting it automatically, which uses the standard formatting.

If you want it in a specific format, then format the DateTime value as a string:

Dim d As DateTime = DateTime.ParseExact(theTime,"HHmm", Nothing);
Dim convertedTime As String = d.ToString("hh:mm tt")