Search code examples
asp.netvb.netdatetimedatetime-conversion

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.


Solution

  • 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