为什么parseexect不起作用?我将日期带入“txtdate.Text”从ajax工具包的日历扩展器和格式设置为“dd / MM / yyyy”,我也将页面文化设置为en-GB。 [英] why parseexect doesnot work some time? i take date into"txtdate.Text" from calender extender of ajax toolkit and format set to "dd/MM/yyyy",also i have set page cultute to en-GB.

查看:153
本文介绍了为什么parseexect不起作用?我将日期带入“txtdate.Text”从ajax工具包的日历扩展器和格式设置为“dd / MM / yyyy”,我也将页面文化设置为en-GB。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

错误是字符串不是有效的日期时间字符串[错误发生在以下代码中:DateTime日期= DateTime.ParseExact(txtdate.Text,dd / MM / yyyy,空值); ]







DateTime date = DateTime.ParseExact(txtdate.Text,dd / MM / yyyy,null);

Convert.ToDateTime(date).ToShortDateString();

Error is" String is not a valid datetime string" [ error occurs at following code: DateTime date = DateTime.ParseExact(txtdate.Text, "dd/MM/yyyy", null); ]



DateTime date = DateTime.ParseExact(txtdate.Text, "dd/MM/yyyy", null);
Convert.ToDateTime(date).ToShortDateString();

推荐答案

我认为你是一个很困惑 - 代码的第二行没有做任何事情:

I think you are a little confused - the second line of your code doesn''t do anything:
DateTime date = DateTime.ParseExact(txtdate.Text, "dd/MM/yyyy", null);
Convert.ToDateTime(date).ToShortDateString();



但重要的是要注意ToShortDateString不返回特定的固定格式 - 特别是它不返回适合与SQL一起使用的字符串。它返回一个字符串,该字符串依赖于在机器中设置的Culture,如果您将它们作为字符串传递,则SQL更喜欢获得''yyyy-MM-dd''格式的日期。

所以有两件事:

首先,通过参数化查询将您的日期作为DateTime传递给SQL(无论如何,您应该始终使用这些来防止SQL注入攻击,这可能会意外或故意破坏您的数据库)。不要将日期转换为streings,除非它是向用户呈现的!



其次,请使用TryParseExact - 它报告问题并允许您记录它和看看它为什么会发生更好的细节,并向用户报告问题。



我想知道问题是否与DateTime格式集有关在客户端计算机上 - 您确定日期是dd / MM / yyyy格式吗?你检查了吗?


But it is important to note that ToShortDateString does not return a specific, fixed format - particularly it does not return a string which is suitable for use with SQL. It returns a string which is dependant on the Culture that is set in teh machine, where SQL prefers to get ''yyyy-MM-dd'' format dates if you hand them through as a string.
So two things:
First, hand your date through to SQL as a DateTime via a parametrized query (you should be using these at all times anyway to prevent an SQL injection attack which can accidentally or deliberately destroy your database). Don''t convert dates to streings unless it s for presentation to the user!

Second, use TryParseExact instead - it reports a problem and allows you to log it and look at why it happened in better detail as well as report the problem to the user.

I''m wondering if the problem is to do with the DateTime format set on the Client machine - are you sure the date is in dd/MM/yyyy format? Have you checked?


这篇关于为什么parseexect不起作用?我将日期带入“txtdate.Text”从ajax工具包的日历扩展器和格式设置为“dd / MM / yyyy”,我也将页面文化设置为en-GB。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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