Convert string of "dd/MM/yyyy" format into Datetime using C#?

I am using the code below to convert my string which is in the format "dd/MM/yyyy" into datetime

//DateStr = 19/02/2017 for example
Datetime date = Convert.ToDatetime(Datestr); 

but it is throwing a runtime error of Invalid type, so how should I convert it into valid Datetime value without getting any error?

Asked by:- Vipin
: 2774 At:- 9/30/2017 8:56:52 AM
C# Datetime-conversion string

2 Answers
profileImage Answered by:- neena

You should use DateTime.ParseExact, to get the correct results

DateTime dt=DateTime.ParseExact("19/02/2017", "dd/MM/yyyy", CultureInfo.InvariantCulture);

Read more about Datetime.ParseExact 

Or You can use DateTime.TryParseExact , it is also same, code will be like this

DateTime dt;
if (DateTime.TryParseExact("19/02/2017", "dd/MM/yyyy", 
    out dt))
    //date is valid, do something here
At:- 10/2/2017 12:04:02 PM
Thanks, but I think DateTime.ParseExact is better to use than TryParseExact 0
By : Vipin - at :- 10/30/2017 10:13:48 AM

profileImage Answered by:- vikas_jk

You can pass your date in the code below

string formattedDate = date.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture)
At:- 10/10/2017 2:42:08 PM

Login/Register to answer
Register directly by posting answer/details

Full Name *

Email *

By posting your answer you agree on privacy policy & terms of use

Subscribe Now

Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly