Asp.Net中的日期时间问题 [英] Date Time Problem in Asp.Net

查看:44
本文介绍了Asp.Net中的日期时间问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ajax日历,以便从文本框中获取日期.

当我从文本框中获取它时,它是一个字符串,就像26/01/2011

我想将其放入数据库中,我的数据库数据类型为DateTime,以便将其转换为DateTime

所以我用了Convert.ToDatetime(txtDate.Text)

然后我得到了26/1/2011 12:00:00 AM

sql server DateTime Datat Type不支持此功能

请帮我做.

我的做法:

i am using ajax calender,so that i am taking date from a textbox.

when i am taking it from textbox,it is a string and like 26/01/2011

and i want to put it in database,my database datatype id DateTime,so that i want to convert it to DateTime

So i used Convert.ToDatetime(txtDate.Text)

Then i got 26/1/2011 12:00:00 AM

This is not supported by sql server DateTime Datat Type

Please help me to do it.

The way i did:

string joindate = txtJdate.Text;
               string dobdate = txtDob.Text;
               DateTime join, dob;
               join = Convert.ToDateTime(joindate);
               dob = Convert.ToDateTime(dobdate);
obj.IDUCommand("insert into tbl_empdetails values(" + dob + "," + join + ")")



相应的sql查询为:

插入tbl_empdetails值(18/1/2011 12 :00:00 AM,25/1/2011 12:00:00 AM)

错误是:

"12附近的语法不正确".



The corresponding sql query is :

insert into tbl_empdetails values(18/1/2011 12:00:00 AM,25/1/2011 12:00:00 AM)

The error is :

" Incorrect syntax near 12 "

推荐答案

这是因为您将其放入数据库的方式所致.您(有意或无意地)将其从DateTime转换为字符串:可能是这样说的:
It''s because of the way you put it into the database. You have (deliberately or accidentally) converted it from a DateTime to a string: probably by saying something like:
SqlCommand com = new SqlCommand("INSERT INTO myTable (date) VALUES (''" + myDateTime + "'')", con);

不幸的是,SQL需要ISO格式的数据字符串:"yyyy/MM/dd hh:mm:ss",您的语言环境默认情况下不会执行此操作.

最好的解决方案是改用参数化查询:

Unfortunatley, SQL expects data strings in ISO format: "yyyy/MM/dd hh:mm:ss" which your locale does not do by default.

The best solution is to use parametrized queries instead:

SqlCommand com = new SqlCommand("INSERT INTO myTable (date) VALUES (@DT)", con);
com.Parameters.AddWithValue("@DT", myDateTime);

这还具有不易于受到SQL注入攻击的优势,值得对所有数据库进行访问.

This has the additional advantage of not being prone to SQL Injection attacks, and is worth doing for all database access.


DateTime DOJ = DateTime.ParseExact(txtJdate.Text,"dd /MM/yyyy,null);
然后传入表及其在我这边工作.
DateTime DOJ = DateTime.ParseExact(txtJdate.Text,"dd/MM/yyyy",null);
then pass in table and its working at my side.


使用以下语句会更好...
using the following statement is better...
DateTime DOJ;
if (DateTime.TryParseExact(txtJdate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out DOJ))
{
//Do what ever u want with that date...   
}
else
{
// invalid date format...
}


这篇关于Asp.Net中的日期时间问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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