正如所有评论所说,但到目前为止没有一个答案说:不要将其作为字符串传递到数据库.
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.
解析可以通过以下方式完成DateTime.ParseExact
or DateTime.TryParseExact
取决于这是否是“可疑”数据(例如来自用户)或应该really是正确的,并且异常是对不可解析值的最合适的反应。我建议你通过CultureInfo.InvariantCulture
使用您的自定义格式字符串。例如:
DateTime date = DateTime.ParseExact(text, "dd/MM/yyyy",
CultureInfo.InvariantCulture);
(如果您做了很多日期/时间工作,您可能还想考虑使用我的野田时间项目 http://noda-time.googlecode.com它允许您以更丰富的方式表达价值 - 在这种情况下您可能会使用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.