Question

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!

Was it helpful?

Solution

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")

OTHER TIPS

Label1.Text = Format(Now, "hh:mm"): Label1's text= 10:26 (or whatever the time is)

Label1.Text = Format(Now, "hh:mm tt"): Label's text = 10:26 PM

Label1.Text = Format(Now, "dddd dd, MMMM, YYYY"): Label1's text = Thursday 21, August, 2014 (or whatever the date is)

Label1.Text = Now.ToShortTimeString.ToString()   (10:26 PM)

Label1.Text = Now.ToLongTimeString.ToString()    (10:26:30 PM) 
Dim theTime = New Date(2012, 6, 12, 14, 0, 0)
Dim formatted = theTime.ToString("h:mm tt", Globalization.CultureInfo.InvariantCulture)

Custom Date and Time Format Strings

There are two ways to achieve this.

Option 1 (using standard date and time format strings):

Dim theTime As DateTime = new DateTime(2008, 4, 10, 6, 30, 0)
Dim convertedTime As String = 
    theTime.ToString("t", CultureInfo.CreateSpecificCulture("en-us"))

Option 2 (using custom date and time format strings):

Dim theTime As DateTime = new DateTime(2008, 4, 10, 6, 30, 0)
Dim convertedTime As String = theTime.ToString("hh:mm tt")

In both cases convertedTime will be 6:30 AM

Try This One...

  Dim TimeNow As String
  TimeNow = TimeOfDay.ToString("h:mm:ss tt")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top