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?
use DateTime.ParseExact
string strDate = "24/01/2013";
DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", null)
null
will use the current culture, which is somewhat dangerous. Try to supply a specific culture
DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", CultureInfo.InvariantCulture)
You can use "dd/MM/yyyy"
format for using it in DateTime.ParseExact
.
Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.
DateTime date = DateTime.ParseExact("24/01/2013", "dd/MM/yyyy", CultureInfo.InvariantCulture);
Here is a DEMO
.
For more informations, check out Custom Date and Time Format Strings
Source: Stackoverflow.com