Bcktr
Bcktr

Reputation: 208

Conversion String to Datetime (24 hour format) is not match

I have a string 10/13/2016 21:42

Dim ETAtime1 As String = Convert.ToDateTime("10/13/2016 21:42").ToString("MM/dd/yyyy HH:mm")
'result is 10/13/2016 21:42

I want the result to be 10/13/2016 21:42 (24 hour format) like the above string. But why, after I have converted it like below, does it become 12 hour format?

 Dim ETAtime As DateTime = DateTime.ParseExact(ETAtime1, "MM/dd/yyyy HH:mm", Nothing)
'result is 10/13/2016 09:42

How to resolve it, it become 09:42 not 21:42? I need DateTime type data not an string.

Upvotes: 0

Views: 4110

Answers (3)

djv
djv

Reputation: 15774

This line takes your string, 10/13/2016 21:42 and parses it using the format provided. This is useful when a date string is in an ambiguous format such as 06/05/2016 and even though this could either represent June 5th or May 6th, but you know that it's day/month, May 6th in my example. For more see DateTime.ParseExact.

Dim ETAtime As DateTime = DateTime.ParseExact(ETAtime1, "MM/dd/yyyy HH:mm", Nothing)

The result of this method is a DateTime, not a string.

'result is 10/13/2016 09:42

So the result is valid - depending how you are inspecting it - however there is no AM/PM indicator. It is already a DateTime. Further operations on ETAtime can prove this.

Dim ETAtime1 As String = Convert.ToDateTime("10/13/2016 21:42").ToString("MM/dd/yyyy HH:mm")
Dim ETAtime As DateTime = DateTime.ParseExact(ETAtime1, "MM/dd/yyyy HH:mm", Nothing)
Console.WriteLine("{0:MM/dd/yyyy HH:mm}", ETAtime)
Console.WriteLine("{0:MM/dd/yyyy hh:mm}", ETAtime)
Console.WriteLine("{0:MM/dd/yyyy hh:mm tt}", ETAtime)

Output

10/13/2016 21:42
10/13/2016 09:42
10/13/2016 09:42 PM

There is really no issue with your code.

My IDE (Visual Studio 2012) displays the date in this format when debugging 10/13/2016 09:42 PM. I am located in the USA. What is displayed should be based on your regional settings. It would be interesting to see a screenshot of yours.

enter image description here

Upvotes: 1

soohoonigan
soohoonigan

Reputation: 2350

A DateTime object doesn't have a "format", think of it as just holding what the date and time actually are. Storing that information in a DateTime object is what allows you to perform mathematical/logical operations on it. How you display the DateTime hours to the user is up to you. The ToString method can display either of those hour formats depending on what format string you pass it...for example:

    Dim ETAtime1 As String = Convert.ToDateTime("10/13/2016 21:42").ToString("MM/dd/yyyy HH:mm")
    Dim ETAtime As DateTime = DateTime.ParseExact(ETAtime1, "MM/dd/yyyy HH:mm", Nothing)

    MsgBox(ETAtime.ToString("HH:mm"))
    'Outputs 21:42
    MsgBox(ETAtime.ToString("h:mm"))
    'Outputs 9:42

Upvotes: 2

irantutors
irantutors

Reputation: 11

try this :

      dddd, MMMM d, yyyy HH:mm:ss tt"

Upvotes: 0

Related Questions