Convert string to DateTime C # [duplicate]

2

How do I get a string something like "01/30/2015", for example, and convert it to datetime and keep that same date format? Being able to validate the date.

    
asked by anonymous 13.10.2015 / 21:14

1 answer

2

You can not keep date format when converting to DateTime . This guy saves a date. Score. To be more precise information from a point in time. It has the date and the time.

If you want it in a specific format to present it somewhere, you will convert it to string , because many formats can only be obtained with texts, and string in> is the type for text. In practice even in simple formats (something like "30012015"), it will also be a string . No matter where you use this information.

You can use DateTime.Parse() to convert. But I almost always prefer TryParse() . . It generates no exception if the data is invalid.

DateTime data;
var dataFormatada = "";
var resultado = DateTime.TryParse("30/01/2015", out data);
if (resultado) {
    dataFormatada = data.ToString("dd/MM/yyyy");
}

Related:

13.10.2015 / 21:20