Convert String with AM/PM to Datetime

Asked

Viewed 435 times

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 method TryParse 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 into account the AM/PM?

2 answers

3


Maybe it’s the case to use TryParseExact() and define 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"));
        }
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

2

Use the format HH:

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.