Convert String with AM / PM to DateTime

2

I have a variable that contains a date with AM / PM:

string data = "01/08/2016 9:00 PM";

When I try to convert to DateTime using the TryParse method, the result ignores the designator "AM / PM".

string data = "01/08/2016 9:00 PM";
DateTime dataOut;
if(DateTime.TryParse(data, out dataOut))
{
   //Restante do código.
   dataOut.ToString(); //Retorna 01/08/2016 09:00, deveria retornar 21:00.
}

How to proceed? What method do I use to perform this conversion, taking AM / PM into consideration?

    
asked by anonymous 31.08.2016 / 22:07

2 answers

2

Maybe it's the case to use TryParseExact() and set the format that will check (I put a format, I do not know if it is the most suitable for you):

using System;
using static System.Console;
using System.Globalization;

public class Program {
    public static void Main(){
        var data = "01/08/2016 9:00 PM";
        DateTime dataOut;
        if(DateTime.TryParseExact(data, "MM/dd/yyyy h:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out dataOut)) {
            WriteLine(dataOut.ToString("MM/dd/yyyy HH:mm"));
        }
        data = "01/08/2016 9:00 AM";
        if(DateTime.TryParseExact(data, "MM/dd/yyyy h:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out dataOut)) {
            WriteLine(dataOut.ToString("MM/dd/yyyy HH:mm"));
        }
    }
}

See working on dotNetFiddle .

    
31.08.2016 / 22:30
1

Use the

HH :

  

The format HH represents the time as a number from 00 to 23 ; The   time is represented by a clock of 24 hours based on zero that   counts the hours since midnight. Single digit time is formatted   with a leading zero.

Code:

string data1 = "01/08/2016 9:00 AM";
string data2 = "01/08/2016 9:00 PM";

DateTime dataOut;

if(DateTime.TryParse(data1, out dataOut)) {
    Console.WriteLine(dataOut.ToString("HH:mm ", CultureInfo.InvariantCulture)); // 09:00
}

if(DateTime.TryParse(data2, out dataOut)) {
    Console.WriteLine(dataOut.ToString("HH:mm ", CultureInfo.InvariantCulture)); // 21:00
}

See DEMO

    

31.08.2016 / 22:24