Convert string to Datetime

Asked

Viewed 3,478 times

2

How to take from a string something like "30/01/2015", for example, and convert it to datetime and maintaining the same date format? You can validate the date.

  • Related http://answall.com/q/68247/10315

  • I saw that question but I thought the answer might be another.

  • https://msdn.microsoft.com/pt-br/library/xhz1w05e(v=vs.110). aspx

  • tranquil @Ayo .

1 answer

3


You cannot keep date format when converting to DateTime. This type keeps a date. Point. To be more accurate a point information in time. It has the date and 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 is the type for text. In practice even in simple formats (something like "30012015"), it will also be a string. It doesn’t matter where you use this information.

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

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

I put in the Github for future reference.

Related:

Browser other questions tagged

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