This question already has an answer here:
- Converting a String to DateTime 12 answers
I am new to DotNet and C#. I want to convert a string in mm/dd/yyyy
format to DateTime
object. I tried the parse function like below but it is throwing a runtime error.
DateTime dt=DateTime.Parse("24/01/2013");
Any ideas on how may I convert it to datetime?
You can use
"dd/MM/yyyy"
format for using it inDateTime.ParseExact
.Here is a
DEMO
.For more informations, check out
Custom Date and Time Format Strings
You need to use
DateTime.ParseExact
with format"dd/MM/yyyy"
Its safer if you use
d/M/yyyy
for the format, since that will handle both single digit and double digits day/month. But that really depends if you are expecting single/double digit values.Your date format
day/Month/Year
might be an acceptable date format for some cultures. For example for Canadian Cultureen-CA
DateTime.Parse
would work like:Or
Both the above lines would work because the the string's format is acceptable for
en-CA
culture. Since you are not supplying any culture to yourDateTime.Parse
call, your current culture is used for parsing which doesn't support the date format. Read more about it at DateTime.Parse.Another method for parsing is using
DateTime.TryParseExact
The
TryParse
group of methods in .Net framework doesn't throw exception on invalid values, instead they return abool
value indicating success or failure in parsing.Notice that I have used single
d
andM
for day and month respectively. Singled
andM
works for both single/double digits day and month. So for the formatd/M/yyyy
valid values could be:For further reading you should see: Custom Date and Time Format Strings
use
DateTime.ParseExact
null
will use the current culture, which is somewhat dangerous. Try to supply a specific culture