how to convert string date to datetime


I have a date in the following format 10/16/2018 or this is in MM / DD / YYYY format so it comes as a parameter, but this date is as string and I need to convert it to a datetime, try the following:

string fecha = "10/16/2018";
DateTime dt = DateTime.Parse(fecha);

And this error is generated: the string can not be recognized as a valid datetime value, please help, however when the date is in DD / MM / YYYY format if it works, but I must have the date in the format above. Thanks

asked by Raidel Fonseca 16.10.2018 в 16:02

3 answers


What you are looking for is a conversion of string to datetime with the format MM / dd / yyyy, for this it is necessary that you establish the correct format such as this MM / dd / yyyy , I leave an example:

The library is required: using System.Globalization;

string dateString = "10/16/2018";
string format = "MM/dd/yyyy";

DateTime dateTime = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);

You can also see it working on this rextester link

answered by 16.10.2018 / 16:29

To solve your problem you have to use DateTime. ParseExact or DateTime.TryParseExact , both allow you to enter the format of the incoming string

string fecha = "10/16/2018";
string formato = "MM/dd/yyyy" //MM representa Mes, dd día e yyyy año

After defining these two data, you could do the following

  bool result = DateTime.TryParseExact(fecha, formato, null, System.Globalization.DateTimeStyles.None, out DateTime dt);

    //En caso de que result sea verdadero, implica que la fecha alojada en el string es válida.
        Console.WriteLine("La fecha es correcta y es {0}", dt.ToShortDateString());
    //Caso contrario, la fecha es invalida.
        Console.WriteLine("El formato de la fecha ingresada es incorrecta.");
answered by 16.10.2018 в 16:31

Use this conversion: you must add CultureInfo because with the American dates the months use them at the beginning and it may give you an error.

DateTime dt = Convert.ToDateTime("10/16/2018", CultureInfo.InvariantCulture); 

Do not forget to add the namespace using System.Globalization;


answered by 16.10.2018 в 16:33