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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
DateTimeto 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.ParseExactorDateTime.TryParseExactdepending 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 inCultureInfo.InvariantCulturewith your custom format string. For example:(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.