Convert string date to system datetime in C#
I want to convert string date to system datetime in C#. The user enters date through textbox and it should be converted as to datetime. I trid following code but its not working...
DateTime ToDate = Convert.ToDateTime(txtToDate.Text);
DateTime FromDate = DateTime.Parse(txtFromDate.Text);
It shows the following exception "String was not recognized as a 开发者_JS百科valid DateTime."
How to do this...???
You could use DateTime.ParseExact()
. That way you can specify the format of the input string, so it will be parsed correctly, for example:
dateString = "Sun 15 Jun 2008";
format = "ddd dd MMM yyyy";
try
{
DateTime result = DateTime.ParseExact(dateString, format, CultureInfo.CurrentCulture);
}
catch (FormatException)
{
}
whatever user enters in your textbox that should be in valid date format, otherwise write your own function to make it in valid format. then Convert it into DateTime format .
for different format you can check this : http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx
for more help you can check similar question on this site : Validate a DateTime in C#
You can of course parse the user's input and rely on the users to always enter a correct date. But I'd recommend to use a specific control for entering a date, such as the calendar control of the ajax control toolkit.
By using such a control, you can prevent invalid input and it's also much easier for the user. If you search for DatePicker or similar, I'm sure you can find lot's of other similar controls.
Ask the user to enter his datetime in a particular format into textbox i.e., either "ddMMyyyyhhmmss"
or "dd/MM/yyyy hh:mm:ss tt"
or "dd-MM-yyyy hh:mm:ss tt"
or some other formats and use the help of following code to convert in to a Valid datetime.
DateTime ToDate = DateTime.ParseExact(txtToDate.Text, <User DateTime format as String>,
System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None)
Instead, if the above coding makes complicated then you can try DateTime.TryParse() also
First of all you have to validate text box value that it is valid or not, you can use ajax MaskeditExtender control for that and restrict the use enter only require date formate.
DateTime dt = Convert.ToDateTime(date); here date is in string.
精彩评论