无法将参数值从String转换为DateTime [英] Failed to convert parameter value from a String to a DateTime

查看:434
本文介绍了无法将参数值从String转换为DateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在页面中,我编写代码:(用于数据插入数据库)

  string  Openingdate = tbopendate.Text; 
myCommand.Parameters.Add( @ Openingdate,System.Data.SqlDbType.DateTime ).Value = Openingdate;





此代码工作正常,没有错误。



但是我在另一个页面写的相同代码&代码是((用于数据插入数据库)。

  string  Joindate = tbJoindate.Text; 
myCommand.Parameters.Add( @ Joindate,System.Data.SqlDbType.DateTime ).Value = Joindate;





此代码显示错误:: 无法从字符串转换参数值到日期时间



为什么&问题出在哪里???

解决方案

我不知道你是如何在第一个中得到错误的。在数据库中都有datetime类型吗?如果是,那么第一个也不应该工作。

你必须转换文本到日期时间

试试这个



 DateTime date = DateTime .ParseExact(tbJoindate.Text.ToString(),
yyyy-MM-dd HH:mm:ss .fff
CultureInfo.InvariantCulture);

cmd.Parameters.Add( @ Joindate,SqlDbType.DateTime ).Value = date;


尝试解析日期。让我们检查给定的tbJoining日期是否是 DATE 。试试这个:

 DateTime dt; 
DateTime.TryParse(tbJoindate.Text.Trim(), out dt);
myCommand.Parameters.Add( @ Joindate,System.Data.SqlDbType.DateTime ).Value = dt;







--Amit


 DateTime date = Format(CDate(tbJoindate.Text),  yyyy-MM- dd
mycommand.parameters.Add( @ Joindate, date);





 DateTime date = DateSerial(Mid(tbJoindate.Text, 7  4 ),Mid(tbJoindate.Text, 4  2 ),Mid(tbJoindate.Text, 1  2 ))
mycommand.parameters.Add( @ Joindate,日期);


In a page, I write the code:(for data insert in to Database)

string Openingdate = tbopendate.Text;
myCommand.Parameters.Add("@Openingdate", System.Data.SqlDbType.DateTime).Value = Openingdate;



This code is working fine, there is no error.

But the same code I write in another page & the code is ((for data insert in to Database).

string Joindate = tbJoindate.Text;
myCommand.Parameters.Add("@Joindate", System.Data.SqlDbType.DateTime).Value = Joindate;



This code is showing error::Failed to convert parameter value from a String to a DateTime.

Why & where is the problem???

解决方案

I don't know how you are not getting error in the first. Are both having datetime type in database? If yes then first one also should not work.
You have to convert text to datetime
Try this
[Edit]

DateTime date = DateTime.ParseExact(tbJoindate.Text.ToString(),
                         "yyyy-MM-dd HH:mm:ss.fff",
                         CultureInfo.InvariantCulture);

cmd.Parameters.Add("@Joindate", SqlDbType.DateTime).Value = date;


Try parsing the date. Let's check whether the given tbJoining date is a DATE or not. Try this:

DateTime dt;
DateTime.TryParse(tbJoindate.Text.Trim(), out dt);
myCommand.Parameters.Add("@Joindate", System.Data.SqlDbType.DateTime).Value = dt;




--Amit


DateTime date=Format(CDate(tbJoindate.Text),"yyyy-MM-dd")
mycommand.parameters.Add("@Joindate",date);


or

DateTime date=DateSerial(Mid(tbJoindate.Text, 7, 4), Mid(tbJoindate.Text, 4, 2), Mid(tbJoindate.Text, 1, 2))
mycommand.parameters.Add("@Joindate",date);


这篇关于无法将参数值从String转换为DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆