Click here to Skip to main content
15,888,027 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
My Software (C#) has a problem formatting a custom Windows DateTime-Format.
I need to be able to convert a Datetime from DD.MMM.YY (09.Mar.12) to a default German DateTime DD.MM.YYYY (09.03.2012)? How can i do this the best way?

The SQL-Server is set to German Datetime, and is not accepting a DateTime-format like DD.MMM.YY (error converting varchar to datetime).

---------------------------------------------
Region Settings:
---------------------------------------------

- Windows System Region is set to Germany
- DatetimeFormat Short "DD.MMM.YY"
- DatetimeFormat Long "DD. MMM . YYYY" (yes, this really has spaces!)


Any suggestions are welcome (as SQL-Query and/or as C# Code).
Posted

Thanks to you all.
I have implemented Bernhard's Solution.
It works fine!

Thank you all.
 
Share this answer
 
set as first command in your query:
set language German
(see here[^] and here[^])
In that case you will be able to convert your datetime
 
Share this answer
 
v2
 
Share this answer
 
First off, always convert dates from strings to DateTime values as soon as possible, and preferably on the machine on which the user typed them - that way there is a good chance that the Culture format matches the way the user has entered them. Or better still, use a DateTimePicker so it is presented in a culture-dependant way and =given to you as a DateTime directly. And try to avoid passing date strings to SQL - you generally have no idea what culture it is working in, so unless you reformat them to ISO standard (yyyy-MM-dd) there will probably be problems later. Pass the DateTime value directly as a parameter, and SQL will understand it regardless of it's source.

If you have to parse a date from a string, and you know exactly what format the date will be in, use DateTime.ParseExact

C#
DateTime dt = DateTime.ParseExact("09.Mar.12", "dd.MMM.yy", CultureInfo.InvariantCulture);
 
Share this answer
 
Do not insert the datetime value as a string! Use a parameterized query, it will handle the date time correctly, not depending from your locale settings.
When you use a string, you will run into problems. Some of our customers in Germany use English server systems, and then the SQL server runs on the server (with US-English Windows settings), while the client computers run on German XP or Win7...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900