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
1
: 9175 At:- 9/30/2017 8:56:52 AM
C# asp.net Datetime-conversion string







3 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", 
                            CultureInfo.InvariantCulture, 
                            DateTimeStyles.None,
    out dt))
{
    //date is valid, do something here
}

OR

Simply

string strDate = "24/01/2013";
DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", null);

Also read:

How to convert datetime from one timezone to another in C#?

2
At:- 10/2/2017 12:04:02 PM Updated at:- 6/25/2021 3:47:07 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)
1
At:- 10/10/2017 2:42:08 PM


profileImage Answered by:- jon

If you have datetime string and want to convert it into Datetime

DateTime myDate = DateTime.ParseExact("2022-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff",
                                       System.Globalization.CultureInfo.InvariantCulture);

You can provide format with DateTime.ParseExact()

OR

DateTime myDate;
if (!DateTime.TryParse(dateString, out myDate))
{
    // handle parse failure
}

Thanks.

1
At:- 6/23/2022 6:49:50 AM






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

Full Name *

Email *




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