设置DateTime格式 [英] Set DateTime format

查看:445
本文介绍了设置DateTime格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码 -

  DateTime timeStamp; 

timeStamp = System.Convert.ToDateTime(y.InnerText);

其中 y.InnerText 11/03/2013 11:35:24



但是,这是打破我的import语句,因为数据库正在寻找格式 -

  2013-03-11 11:35:24 

如何设置DateTime对象的格式?

解决方案

blockquote>

如何设置DateTime对象的格式?


你不能。 DateTime 值不要具有格式,除 int double 值。当您要将它们转换为/从字符串 时,您可以指定任何格式信息。



相反,您应该使用参数化SQL并避免首先将 DateTime 值转换为字符串。这是一般的最佳做法 - 不要在SQL字符串中包含值;参数化SQL具有多重优点:




  • 它避免了 SQL注入攻击

  • 它避免了像这样的转换问题

  • 它使您的代码(SQL)与数据(参数值)分开



我会建议,而不是使用 Convert.ToDateTime ,您在解析时指定预期格式。例如:

  timeStamp = DateTime.ParseExact(y.InnerText,
dd / MM / yyyy HH:mm :ss,
CultureInfo.InvariantCulture);

基本上,我尝试应用的两个规则是:




  • 避免执行任何转换,您不需要。如果您确保每个系统尽可能使用正确的数据类型,您通常不需要进行任何转换。

  • 您在哪里执行需要转换为/从字符串表示,对您要消费/生成的表示非常明确。对于机器可读值,通常应该使用不变文化和可能的自定义日期/时间格式。对于人类可读的值,通常应使用用户的文化和标准的日期/时间格式。


I have the following code -

DateTime timeStamp;

timeStamp = System.Convert.ToDateTime(y.InnerText);

Where y.InnerText is 11/03/2013 11:35:24.

However this is breaking my import statement as it the database is looking for the format -

2013-03-11 11:35:24

How can I set the format of the DateTime object?

解决方案

How can I set the format of the DateTime object?

You can't. DateTime values don't have formats, any more than int or double values do. When you want to convert them to/from strings, that's where you specify any formatting information.

Instead, you should use parameterized SQL and avoid converting the DateTime value back into a string in the first place. This is a general best practice - don't include values in your SQL string; parameterized SQL has multiple benefits:

  • It avoids SQL injection attacks
  • It avoids conversion issues like this one
  • It keeps your code (SQL) separate from your data (parameter values)

I would also suggest that instead of using Convert.ToDateTime, you specify your expected format when parsing. For example:

timeStamp = DateTime.ParseExact(y.InnerText,
                                "dd/MM/yyyy HH:mm:ss",
                                CultureInfo.InvariantCulture);

Basically, the two rules I try to apply are:

  • Avoid performing any conversions where you don't have to. If you make sure that every system uses the right data types as far as possible, you often don't need to make any conversions at all.
  • Where you do need to convert to/from string representations, be very explicit about the representation you want to consume/produce. For machine-readable values, that should usually use the invariant culture and possibly a custom date/time format. For human-readable values, that should usually use the user's culture and a standard date/time format.

这篇关于设置DateTime格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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