转换DD / MM / YYYY以YYYY / MM / DD? [英] Convert dd/MM/yyyy to yyyy/MM/dd?

查看:259
本文介绍了转换DD / MM / YYYY以YYYY / MM / DD?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个字符串'30 /二千○一十二分之一十二转换'到'二○一二年十二月三十○日。我的应用程序设置为en-CA,然而数据库接受YYYY / MM / DD作为默认值。


  

我怎么能做到这一点,而不取决于当前的文化信息集
  在服务器?



解决方案

由于所有的评论都表示,但至今没有一个答案说:不要将此作为一个字符串

尽早解析您收到任何文字,然后用的DateTime 重新present它的处处的东西,包括你怎么送它的数据库中,通过参数化SQL 1 。这同样适用于所有类型的值:它的转换成的自然类型的数据,尽快,并保持它在自然再presentation为尽可能长时间。一个日期是不是一个字符串,你只应该将其转换为字符串,如果你真的,真的需要 - 最好的只是把它显示给用户之前

解析功能也可以用 DateTime.ParseExact DateTime.TryParseExact 取决于这是否是可疑数据(例如,从一个用户),或应的真正的是正确的并且已例外是不可解析值最合适的反应数据。我建议你​​在 CultureInfo.InvariantCulture 通过您的自定义格式字符串。例如:

 日期时间日期= DateTime.ParseExact(文字,DD / MM / YYYY
                                    CultureInfo.InvariantCulture);

(如果你做了很多的日期/时间的工作,你可能还需要考虑使用我的野田佳彦时项目,它允许你前preSS以更丰富的方式的价值 - 在这种情况下,你可能会使用 LOCALDATE


1 如果你还没有使用参数化的SQL,而是将其直接烘烤值到SQL,你有超过日期/时间转换更大的问题。

I want to convert a string '30/12/2012' to '2012/12/30'. My application is set to "en-CA" however the database accepts yyyy/MM/dd as default.

How can I do this without depending on the current culture info set at server?

解决方案

As all the comments have said, but none of the answers have said so far: don't pass this to the database as a string.

Parse any text you receive as early as possible, then use DateTime to represent it everywhere else, including how you send it to the database, via parameterized SQL1. This goes for values of all kinds: convert it into the "natural" type for the data as soon as possible, and keep it in that natural representation for as long as possible. A date isn't a string, and you should only convert it to a string if you really, really need to - ideally just before displaying it to a user.

The parsing can be done with DateTime.ParseExact or DateTime.TryParseExact depending on whether this is "suspicious" data (e.g. from a user) or data which should really be correct and for which an exception is the most appropriate reaction to unparseable values. I suggest you pass in CultureInfo.InvariantCulture with your custom format string. For example:

DateTime date = DateTime.ParseExact(text, "dd/MM/yyyy",
                                    CultureInfo.InvariantCulture);

(If you do a lot of date/time work, you may also want to consider using my Noda Time project which allows you to express the value in a richer way - in this case you'd probably use LocalDate.)


1 If you're not already using parameterized SQL, but are instead baking values directly into the SQL, you have bigger problems than date/time conversions.

这篇关于转换DD / MM / YYYY以YYYY / MM / DD?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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