[英]How to save date to SQL SERVER from textbox using ASP.NET
I want to save the date of LeaveFrom and LeaveTo.我想保存 LeaveFrom 和 LeaveTo 的日期。 I have tried this coding below.我在下面尝试过这种编码。 But it says that String was not recognized as a valid DateTime.但它说String 未被识别为有效的 DateTime。
string leavefrom = datepicker1.Text;
DateTime lFrom = Convert.ToDateTime(leavefrom); //error occurs here
string leaveto = datepicker2.Text;
DateTime lTo = Convert.ToDateTime(leaveto);
From what I can see, the line that throws that error is between LINE 1 and LINE 3 wherein the conversion takes place.从我所见,引发该错误的行位于发生转换的第 1 行和第 3 行之间。
Instead of using Convert.ToDateTime()
function to convert the date, use DateTime.ParseExact() wherein it allows you specify the format set within the datepicker control.不是使用Convert.ToDateTime()
函数来转换日期,而是使用DateTime.ParseExact() ,它允许您指定日期选择器控件中设置的格式。
Assuming the format set in datepicker is dd MMM yyyy
(eg. 15 Feb 2018
).假设 datepicker 中设置的格式是dd MMM yyyy
(例如15 Feb 2018
)。 You can simply specify it in the function's parameter:您可以简单地在函数的参数中指定它:
string leavefrom = datepicker1.Text;
DateTime lFrom = DateTime.ParseExact(leavefrom, "dd MMM yyyy", CultureInfo.InvariantCulture);
As @john mentioned use DateTime.ParseExtract()
since you have not mentioned the format of date in String i can't not point you towards exact format but using ParseExtract
you can specify format like正如@john 提到的那样使用DateTime.ParseExtract()
因为你没有提到 String 中的日期格式我不能不指向你确切的格式但是使用ParseExtract
你可以指定格式
DateTime.ParseExact(leavefrom, "dd/MM/yyyy", CultureInfo.InvariantCulture);
Hope this helps.希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.